C+中的指针混淆+; 我的C++课程中的幻灯片让我感到困惑。一方面,在示例1中 int(*foo)[5]是指向5个元素的整数数组的指针,但在示例2中 int(*numbers2)[4]指向整型数组(4个数组)的数组。这两个函数如何具有相同的左手声明,但持有不同的类型 #include <iostream> using std::cout; using std::endl; int main() { //Example1 int numbers[5] = { 1,2,3,4,5 }; int(*foo)[5] = &numbers; int *foo1 = *foo; //Example2 int numRows = 3; int(*numbers2)[4] = new int[numRows][4]; delete[] numbers2; return 0; } #包括 使用std::cout; 使用std::endl; int main(){ //例1 整数[5]={1,2,3,4,5}; int(*foo)[5]=&number; int*foo1=*foo; //例2 int numRows=3; 整数(*numbers2)[4]=新整数[numRows][4]; 删除[]编号2; 返回0; }

C+中的指针混淆+; 我的C++课程中的幻灯片让我感到困惑。一方面,在示例1中 int(*foo)[5]是指向5个元素的整数数组的指针,但在示例2中 int(*numbers2)[4]指向整型数组(4个数组)的数组。这两个函数如何具有相同的左手声明,但持有不同的类型 #include <iostream> using std::cout; using std::endl; int main() { //Example1 int numbers[5] = { 1,2,3,4,5 }; int(*foo)[5] = &numbers; int *foo1 = *foo; //Example2 int numRows = 3; int(*numbers2)[4] = new int[numRows][4]; delete[] numbers2; return 0; } #包括 使用std::cout; 使用std::endl; int main(){ //例1 整数[5]={1,2,3,4,5}; int(*foo)[5]=&number; int*foo1=*foo; //例2 int numRows=3; 整数(*numbers2)[4]=新整数[numRows][4]; 删除[]编号2; 返回0; },c++,C++,检查: 由于数组到指针的隐式转换,指向 数组的第一个元素可以用表达式初始化 数组类型: int a[2]; int* p1 = a; // pointer to the first element a[0] (an int) of the array a int b[6][3][8]; int (*p2)[3][8] = b; // pointer to the first element b[0] of the array b, // which i

检查:

由于数组到指针的隐式转换,指向 数组的第一个元素可以用表达式初始化 数组类型:

int a[2];
int* p1 = a; // pointer to the first element a[0] (an int) of the array a

int b[6][3][8];
int (*p2)[3][8] = b; // pointer to the first element b[0] of the array b,
                     // which is an array of 3 arrays of 8 ints
因此,从本质上讲,左手的
numbers2
foo
在右手边指向什么很重要

因此,在下面的
numbers2
中,指向(尚未命名)数组的第一个元素,该数组是一个4个整数的
numRows数组

 int(*numbers2)[4] = new int[numRows][4];
foo
指向
numbers
的第一个元素,它是一个5个整数的数组

int(*foo)[5] = &numbers;

例2的问题中的描述不完全正确

尝试这样的措辞,你会看到平行性

  • foo
    是指向第一个对象的指针,每个对象是由5个元素组成的整数数组。(事实证明,第一个是唯一的一个)
  • numbers2
    是指向第一个对象的指针,每个对象是由4个元素组成的整数数组。(事实证明,总共有
    numrow

指针数据类型不会告诉您它指向的对象的数量,只会告诉您每个对象的类型。

numbers2
指向动态数组的第一个元素。这就是现在的
新的
表达式的工作原理。想一想。。。如果分配一个普通整数数组,则
newint[numRows]
return
int*
。因此,当您分配一个数组时,您会得到一个指向数组的指针,
int(*)[4]
(在您的特定情况下)。
int*
可以指向单个整数或整数数组的第一个元素的地址。指向数组的指针也是如此。它可以指向单个数组或数组数组的第一个元素的地址。