Possible Duplicate:
is this a variable or function
I mistakenly used something like:
int *arr = new int(100);
and it passes compile, but I knew this is wrong. It should be
int *arr = new int[100];
What does the compiler think it is when I wrote the wrong one?
The purpose of new is to simply reserve memory for storing an int variable on the heap instead of the traditional stack. The main advantage of using heap is that you can store a large number of int variables like in an array of 100000 elements easily on the heap.
int *array = new int[n]; It declares a pointer to a dynamic array of type int and size n . A little more detailed answer: new allocates memory of size equal to sizeof(int) * n bytes and return the memory which is stored by the variable array .
Yes. That's kind of my point. If you make a new variable and see that's it's zero, you can't straight away assume that something within your program has set it to zero.
Allocates an int on the stack and sets its value to 100. int A=new int(); Allocates an int on the stack (yes, value types are always allocated on the stack, even with the new keyword) and sets its value to the default, that is, 0. Follow this answer to receive notifications.
The first line allocates a single int
and initializes it to 100
. Think of the int(100)
as a constructor call.
Since this is a scalar allocation, trying to access arr[1]
or to free the memory using delete[]
would lead to undefined behaviour.
Wikipedia new(C++) quote:
int *p_scalar = new int(5); //allocates an integer, set to 5. (same syntax as constructors) int *p_array = new int[5]; //allocates an array of 5 adjacent integers. (undefined values)
In the current Wikipedia article new
and delete
(C++) the example is removed.
Additionally here's the less intuitive but fully reliable C++ reference for new
and new[]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With