Click here to Skip to main content
15,914,905 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
help me in explaining this one

new1=new node[sizeof(node)];
Posted
Comments
Richard MacCutchan 10-Nov-11 5:26am    
It doesn't look right.

Here, if the type of new1 is node* then your statement will create the array of node object of size of node structure.
 
Share this answer
 
new will allocate requested memory to a pointer variable/object.
C++
int* n=new int[5]; 
will allocate 5 integer bytes of memory to pointer n (5 * 4 = 20 bytes will be allocated, considering int size is 4 bytes in the system).
sizeof will return memory size of the given data type.
C++
int s=sizeof(int); 
On executing this line, s will have value 4, considering int size is 4 bytes in the system).

On your code, "node" should be a structure or a class. "new1" is the pointer of type "node". You are allocating 1 object memory and creating object for "node". Allocated memory address will be stored in "new1" pointer. But, if sizeof(node) returns 20, 20 * sizeof(node) bytes will be allocated to new1 object.

C++
new1=new node[sizeof(node)]; 


Note that you need to call
C++
delete[] new1;
at end to deallocate the memory you consumed for new1.
 
Share this answer
 
v2
Ok, I will try to explain.

First, this seems to be coded by someone who does not really understand the concepts of new and delete, and is rather used to malloc and free.

Second, apparently, new1 is, or should be a variable of type node*. If it is not, then probably the whole line doesn't do what the author intended.

Third, the expression allocates and initializes an array of (sizeof(node)) elements of type node. The initialization happens by calling the constructor node::node() of every element. If you ask me, the sizeof(node) part is a remnant of a former malloc command, and, in fact a mistake, as indicated above.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900