c++ - 指向数组的指针

标签 c++

谁能告诉我为什么第二个和最后一个会收到编译时错误?

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/

相关文章:

c++ - 答案回顾 - 从 'const char*' 到 'char' 的无效转换

c++ - 为什么 Main 函数上的 Sleep() 会停止所有线程?

C++ 日期和时间,带毫秒

c++ - Qt 中的 QDesktopWidget availableGeometry() 无法正常工作,需要垂直滚动才能查看完整图像

c++ - __declspec(dllimport) 实际上是如何工作的?

c++ - 类局部类型可以在定义之前在模板类中使用吗

c++ - 如何在 C++ 或 C 中将字符串转换为条件表达式

C++/VS2005 : Defining the same class name in two different . cpp文件

c++ - 需要知道如何检查输入的字符串是否已在 C++ 中的线程安全记录器内终止

c++ - 使用循环在 C++ 中移动 Sprite (SFML)