什么样的变量是int * [2]?如在演化中int * p2 [2]

时间:2016-04-26 18:23:34

标签: c++ arrays pointers

int* p1;

只是一个指针。当与new []一起使用时,它可以像数组或迭代器一样递增。这很好,但是什么是

int* p2[2];

它看起来应该是一个指向带有两个元素的数组的指针,对吧?但如果我制作一个双元素数组,我就无法指出它。无论如何我无法找到p2指向的东西。下面的很多内容只是尝试了不同的任务,但p2 =& arr没有工作让我感到惊讶。什么是int * [2],它与int(*)[2]有什么不同?

int main()
{
    int arr[2];

    int* p1;            //pointer to int, can be used like an array
    int* p2[2];         //pointer to an array


    p1 = new int[2];
    p1 = arr;
    //p1 = &arr;        //cannot convert ‘int (*)[2]’ to ‘int*’ in assignment

    //p2 = &arr;        //incompatible types in assignment of ‘int (*)[2]’ to ‘int* [2]’
    //p2 = &p1;         //incompatible types in assignment of ‘int**’ to ‘int* [2]’

    //p2 = new int[2];  //incompatible types in assignment of ‘int*’ to ‘int* [2]’
    //p2 = arr;         //incompatible types in assignment of ‘int [2]’ to ‘int* [2]’


}

3 个答案:

答案 0 :(得分:4)

包含2个元素的数组,每个元素都是指向int的指针。

cdecl.org是您完成这些任务的朋友:

enter image description here

答案 1 :(得分:0)

p2是指向int的指针的数组,其大小为2.您可以将p1存储在p2中:

p2[i] = p1; 

如果你想要一个指针到你拥有的数组:

int (*ptr)[2];

您可能需要阅读spiral rule,这是了解更详细说明的简单方法。

答案 2 :(得分:0)

解读复杂外观声明的一种方便方法是从右到左阅读:

int* p2[2];

如果你read from right to left,你得到:包含两个指向int的元素的数组。