Is there a reason why dynamically allocating memory using the 'new' keyword sometimes produces a pointer and sometimes it doesn't? [duplicate]

2 weeks ago 20
ARTICLE AD BOX

The type of pointer to a single element of type T is T*, whereas the type of pointer to an array of Ts is T(*)[N].

new returns a pointer to the allocated T, and new[] returns a pointer to the 1st element of the allocated array, not a pointer to the array itself. That is why both operators return the same T* type.

Conversely, delete takes the address returned by new, and delete[] takes the address returned by new[].

Following the same logic, I thought that here, newNums would be a pointer that points to the newly allocated memory for an array of three ints:

Yes, it is. But, it is a pointer to the first element of the array, and the address of the 1st element is guaranteed to be the same address as the array itself.

However, newNums is not of type int* but rather of type int, since the following code produces the error a value of type "int *" cannot be assigned to an entity of type "int"

That is an incorrect assumption due to wrong code. You are indeed trying to assign an int* pointer to an int element, which is an error. new int[3] allocates an array and returns a pointer to its 1st element, then newNums[0] dereferences that pointer to access the 1st array element.

If you want to assign the value of the int pointed by pointer to the int referred by newNums[0] then you need to dereference pointer, eg:

#include <iostream> int main() { int num = 123; int* pointer = &num; int* newNums = new int[3]; newNums[0] = *pointer; // ^- add this delete[] newNums; }

I am wondering, why in the first case, a pointer is produced, but in the second case no pointer is produced?

That is not correct. A pointer is produced in both cases.

is newNums a pointer?

Yes. It is a pointer to the 1st element of the allocated array.

Read Entire Article