dynamically allocated single vars/arrays

closed account (4ET0pfjN)
Hi, I am confused as why there are two ways to dynamically alllocate memory:

1
2
3
4
int size = 12;
int *anArray = new int[size]; 
anArray[4] = 7;
delete[] anArray;


versus

1
2
3
int *box = new int;
box[4] = 7;
delete box;


Why can't I just do it with the bottom way (saves typing)...Unless of course it was changes made to C++ architecture so just like we can type:

long int x = 9 or long x = 9;

But it CRASHES if I attempt to output box[4] with cout...why is that

**So I guess my question is what's the point of dynamically allocating memory for a single variable if we know it's size. For array, it makese sense so I mean:i
1
2
nt size = 12;
int *anArray = new int[size]; 

so is it b/c we may want to initialize a single variable and not declare it until run time for whatever reason...
Last edited on
The first code fragment creates an array of 12 ints with dynamic storage duration and accesses the element number 4 of that array.

The second code fragment creates a single integer with dynamic storage duration, and then attempts to access the element number 4 of some non-existent array. That access, box[4] = 7; invokes undefined behavior: anything at all may happen, now or later. It's a type of programming error.

The point of "dynamically allocating" a single variable is to create an object with dynamic storage duration, that is, object whose destructor won't be called at the end of scope.

Needless to say, the appropriate way to allocate 12 integers in C++ is actually

1
2
int size = 12;
std::vector<int> anArray(size);
Last edited on
closed account (4ET0pfjN)
Actually, I tried with Linux terminal and it doesn't crash with cout << box[4] just with windows command prompt..
As noted:
undefined behavior: anything at all may happen, now or later.


Just because nothing happens when you do something wrong, doesn't mean doing it is right/correct.
Topic archived. No new replies allowed.