簡體   English   中英

C++中的指針混淆

[英]Pointers Confusion in 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;

}

檢查指針聲明參考

由於數組到指針的隱式轉換,指向數組第一個元素的指針可以用數組類型的表達式初始化:

 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指向臨時(尚未命名)數組的第一個元素,該數組是numRows數組的 4 個整數

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

foo指向numbers第一個元素,它是一個包含 5 個整數的數組

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

您對示例 2 問題的描述不完全正確。

嘗試這樣的措辭,你會看到並行性。

  • foo是指向第一個對象的指針,每個對象都是一個包含 5 個元素的整數數組。 (事實證明,第一個是唯一的)
  • numbers2是指向第一個對象的指針,每個對象都是一個包含 4 個元素的整數數組。 (事實證明,它們總共有numRows

指針數據類型不會告訴您它指向的對象數量,而只會告訴您每個對象的類型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM