2
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.

2
  • 1
    The second one isn't even an array, it's a single int object. To create an array of int* with new, you'd be looking at int** array = new int[60]. Commented Jul 12, 2016 at 2:32
  • Yes, I just noticed that now, for some reason I thought that it would create an array. But I read the documentation and the first parameter of the int constructor becomes the value. Commented Jul 12, 2016 at 2:34

5 Answers 5

11
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*.)

Sign up to request clarification or add additional context in comments.

Comments

2

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;
}

Comments

0

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,

debug view

1 Comment

Yes, it is supposed to be new int[5], new int(5) only creates a pointer of an int of value 5
0

One of them creates an array, the other doesn't.

int * array[60]; // Creates an array of 60 integer pointers

Comments

-1

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.