int* p1;
只是一個指針。當與new []一起使用時,它可以像數組或迭代器一樣遞增。這很好,但什麼是什麼樣的變量是int * [2]?如在分層int * p2 [2]
int* p2[2];
它看起來應該是一個指向具有兩個元素的數組的指針,對嗎?但是如果我創建一個兩元素數組,我不能指向它。無論如何我無法找到讓p2指向某個東西的方法。下面的很多隻是嘗試不同的作業,但它沒有工作,這真的讓我感到驚訝。那麼什麼是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]’
}
'int * p2 [2];'是一個指向'int'的兩個指針的數組。如果你不確定這樣的聲明是什麼意思,請使用[cdecl.org](http://cdecl.ridiculousfish.com/?q=int*+p2%5B2%5D)。 –
當然是。只是其中一個... – roro
如果你想要一個指向數組的指針,那就是'int(* p2)[2];'。請注意,在這種情況下,數組的大小很重要 - 如果(例如)您增加了'p2',它將以2'int'數組的大小增加。 –