谁能告诉我为什么第二个和最后一个会收到编译时错误?
void test(){
int array[10]{};
int (*i) [10] = &array; // works
int (*j) [10] = array; // does not work
int *k = array; // works
int *l = new int[10](); // works
int (*m) [10] = new int[10](); // does not work
exit(0);
}
我不确定为什么第二个在没有&符号的情况下不起作用,因为 array 和 &array 引用相同的地址。最后,我认为这是因为它无法告诉我们正在专门动态分配数组,但我想确认这一点。
最佳答案
在某些情况下,I'm not sure why the second does not work without the ampersand since array and &array refer to the same address.
int (*j) [10] = array;
array
会衰减为 int*
而不是 int (*)[10]
。因此,即使array
和&array
的值相同,但类型不同。 array
衰减前的类型为 int [10]
,衰减为 int*
,而 &array
的类型为int (*)[10]
。
因此,错误告诉您我们无法使用 int*
(在左侧键入)初始化 int(*)[10]
(在左侧键入)腐烂后的右手边)。
error: cannot convert ‘int*’ to ‘int (*)[10]’ in initialization
同样,在最后一种情况下 int (*m) [10] = new int[10]()
右侧的类型是 int*
,它不能用于初始化左侧的类型(int (*)[10]
)。
关于c++ - 指向数组的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74918627/