[英]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
. array
只是一个指针,然后指向一个初始化值为60
的int。
If you meant int * array = new int[60];
如果你的意思是
int * array = new int[60];
, array
will point to an array of 60 ints, they're still not the same thing. ,
array
将指向一个60个整数的数组,它们仍然不是一回事。
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). 请注意,就像声明一样,
int* array
意味着它是一个指针 ,而int* array[60]
意味着它是一个数组 (60个指针)。 (Array might decay to pointer, ie int**
for int* array[60]
, it's not same as int*
.) (数组可能会衰减为指针,即
int**
为int* array[60]
,它与int*
。)
Perhaps you do not realize that the second case is not an array, the following program prints 60
: 也许你没有意识到第二种情况不是数组,下面的程序打印
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];
要创建指针int 数组,请使用
int * array = new int[5];
其中一个创建一个数组,另一个没有。
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. 为了帮助理解差异,请考虑第一行在内存中创建一个60指针块(例如,如果你在main中,则在堆栈中),但第二行只是一个指针块。
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). 在第一行中,您更改第一个指针,在第二行中,您将1添加到整数(更改为61)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.