C++ challenge question not clear | Sololearn: Learn to code for FREE!
¡Nuevo curso! ¡Todo programador debería aprender IA Generativa!
Prueba una lección gratuita
0

C++ challenge question not clear

Hello, Can someone explain why int *arr = new int[5]; is valid but int *arr = new int; is not? I found this in a C++ challenge. Thank you.

18th May 2019, 11:34 AM
Alfredo Caroli
Alfredo Caroli - avatar
4 Respuestas
+ 9
int *arr = new int[5]; Is valid as because there is dynamic allocation of an array of integer type till the size It declares a pointer to a dynamic array of type int and size 5. new allocates memory of size equal to sizeof(int) * 5 bytes and return the memory which is stored by the variable array. So this is valid. int *arr = new int; In this case The new operator is allocating space for a block of n integers which not describe and assigning the memory address of that block to the int*variable array so how much space should be allocated to an variable length array is not defined and it can take so much wastage of memory so it's invalid. and once dynamically allocated memory need to be deallocated so delete() or free() is used to free the memory space after work done but in second case that is not identical to when to use the delete() or free() for free the memory after allocation.
18th May 2019, 11:41 AM
GAWEN STEASY
GAWEN STEASY - avatar
+ 9
Alfredo Caroli that's above challenge may be based for an array that's why I said that. In normal for dynamically allocated single variable then we use this type of declaration of pointer int *p = new int; Pointer syntax can be as pointer-variable = new data-type(value); Example: int *p = new int(5); allocate 5 to p int *p = new int[10]; Which allocate continuously 10 variables to the memory which all is of integer type https://www.geeksforgeeks.org/new-and-delete-operators-in-cpp-for-dynamic-memory/ any C++ expert can correct me on this or give you more details with your query.
18th May 2019, 12:14 PM
GAWEN STEASY
GAWEN STEASY - avatar
0
https://code.sololearn.com/cCnkR0KFj8aP/?ref=app This is the code in the C++ course, "Dynamic Memory" section. Looks like it's valid here.
18th May 2019, 11:51 AM
Alfredo Caroli
Alfredo Caroli - avatar
0
The question was just "Which of the following statements is valid?", so it didn't refer to arrays. Thank you very much for your reply, I guess I will just report the question as not clear.
18th May 2019, 12:26 PM
Alfredo Caroli
Alfredo Caroli - avatar