Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "new int(100)" do?

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?

like image 999
JASON Avatar asked Dec 10 '12 09:12

JASON


People also ask

What does new int do in C++?

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.

What does new int *[ N mean?

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 .

Does new int initialize to zero?

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.

What does new int mean in C#?

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.


2 Answers

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.

like image 85
NPE Avatar answered Oct 04 '22 02:10

NPE


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) 

UPDATE

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[].

like image 33
Peopleware Avatar answered Oct 04 '22 02:10

Peopleware