FrozenFeet
FrozenFeet

Reputation: 11

Dynamic array only allocating one element

I have searched all over and have not found anything on this.

I have the following simple code:

#include<iostream>

using namespace std;

int main() {
int *newArray;
int size;

cout << "enter size: ";
cin >> size;
newArray = new int[size];

cin.get();
return 0;

For some reason, regardless of the number entered, the dynamic array always has only one element allocated. I am not getting any compiler errors or run time errors (other than the array issue). I have also tried

int *newArray;
newArray = new int[100];

and

const int SIZE = 100;
int *newArray;
newArray = new int[SIZE];

I get the same result. I am using Visual Studio Community 2015 for my IDE if that makes a difference. If anyone has any pointers (no pun intended) please let me know. Thank you.

Upvotes: 0

Views: 1486

Answers (1)

George Sovetov
George Sovetov

Reputation: 5238

newArray is not an array, it's just a pointer to some place in memory. It doesn't contain a number of elements, it's just an address in memory. When you do newArray = new int[n], sizeof(int)*n bytes of memory are allocated and the address of this allocated space is saved in newArray.

Visual Studio only knows that newArray is a pointer to an int. So it just shows the one number at that address. It cannot know how much memory has been allocated there.

If you want to see more than the first int, open the memory view, type newArray as the address, set up it to show ints. You will see plain memory interpreted as integers, so you will see numbers from your array. But there will be no end of these ints. After your numbers, there will be garbage.

Another option to try (I'm not sure if it works though) is to add (int[100])newArray to the Watch window.

So memory is allocated, feel free to write and read it and don't forget to delete[] it.

Upvotes: 1

Related Questions