指针在C ++中的混乱

时间:2016-10-02 17:43:28

标签: 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;

}

2 个答案:

答案 0 :(得分:3)

检查pointer declaration reference

  

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

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

从本质上讲,左手numbers2foo指向右边的事情。

所以在跟随numbers2指向temporary(尚未命名)数组的第一个元素时,该数组是一个包含4个整数的numRows数组的数组

 int(*numbers2)[4] = new int[numRows][4];

虽然foo指向numbers的第一个元素,这是一个包含5个整数的数组

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

答案 1 :(得分:2)

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

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

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

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