Reputation: 628
int * array[60]; //creates an array of 60 pointers to an int
int * array = new int(60); //same thing?
Do these both result in the same type of array? e.g an array of pointers to integers
I know that the first one uninitialized, and the second one is initialized, but I am unsure of what exactly the second one creates.
Upvotes: 2
Views: 1619
Reputation:
One of them creates an array, the other doesn't.
int * array[60]; // Creates an array of 60 integer pointers
Upvotes: 0
Reputation: 172924
int * array = new int(60); //same thing?
No, they're not the same thing. array
is just a pointer here, and then point to an int with initialized value 60
.
If you meant int * array = new int[60];
, array
will point to an array of 60 ints, they're still not the same thing.
Note that just as the declaration, int* array
means it is a pointer, while int* array[60]
means it is an array (of 60 pointers). (Array might decay to pointer, i.e. int**
for int* array[60]
, it's not same as int*
.)
Upvotes: 11
Reputation: 831
To help understand the difference, take into account that the first line creates a 60 pointers-block in memory (in the stack if you are inside main, for example), but the second one only a pointer block.
Both are completely different types. For example, try the following:
array++;
In the first line, it does not work. In the second one, it's ok. If you try:
array[0]++;
In the first line you change the first pointer, in the second one you add 1 to the integer (change to 61).
Upvotes: -1
Reputation: 66
Here are two pictures that illustrate the differences between
int * array[5];
and
int * array = new int(5);
To create a pointer int array use int * array = new int[5];
code,
Upvotes: 0
Reputation: 5894
Perhaps you do not realize that the second case is not an array, the following program prints 60
:
#include <iostream>
int main() {
int* foo = new int(60);
std::cout << *foo << '\n';
return 0;
}
Upvotes: 2