简体   繁体   中英

Difference between int * array[60] and int * array = new int(60);

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? eg 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.

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, ie int** for int* array[60] , it's not same as int* .)

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

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

其中一个创建一个数组,另一个没有。

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM