Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this dynamic allocation do?

Today, I found out that you can write such code in C++ and compile it:

int* ptr = new int(5, 6);

What is the purpose of this? I know of course the dynamic new int(5) thing, but here i'm lost. Any clues?

like image 922
Stringer Avatar asked Feb 26 '10 23:02

Stringer


People also ask

What does dynamic memory allocation do?

Dynamic memory allocation is the process of assigning the memory space during the execution time or the run time. Reasons and Advantage of allocating memory dynamically: When we do not know how much amount of memory would be needed for the program beforehand.

What does it mean by dynamically allocated?

Dynamic memory allocation is when an executing program requests that the operating system give it a block of main memory. The program then uses this memory for some purpose. Usually the purpose is to add a node to a data structure.

How do you dynamically allocate?

To allocate space dynamically, use the unary operator new, followed by the type being allocated. These statements above are not very useful by themselves, because the allocated spaces have no names!


3 Answers

You are using the comma operator, it evaluates to only one value (the rightmost).

The comma operator (,) is used to separate two or more expressions that are included where only one expression is expected. When the set of expressions has to be evaluated for a value, only the rightmost expression is considered.

Source

The memory address that the pointer is pointing to is initialized with a value of 6 above.

like image 163
Brian R. Bondy Avatar answered Sep 18 '22 22:09

Brian R. Bondy


My compiler, g++, returns an error when attempting to do this.

What compiler or code did you see this in?

like image 30
McPherrinM Avatar answered Sep 20 '22 22:09

McPherrinM


I believe it is bug which meant to allocate some sort of 2D array. You can't do that in C++ however. The snippet actually compiles because it's utilizing the comma operator, which returns the last expression and ignores the results of all the others. This means that the statement is equivalent to:

int* ptr = new int(6);
like image 38
MikeP Avatar answered Sep 21 '22 22:09

MikeP