1
經過多次試驗我已經成功與新表達分配指針的3 int
秒的陣列。在下面的代碼片段中,我首先展示了這個指針在堆棧中的用法,然後在多次嘗試之後顯示堆分配的位置。我成功地分配了一個指向堆中3個整數的指針,但我仍然不明白對數組的訪問如何工作?
#include <iostream>
int main()
{
// First, pointer p to an array of 3 int's in the stack.
int a[3] = { 10, 11, 12 };
int(*p)[3] = &a;
std::cout << **p << " " << *(*p + 1) << " " << *(*p + 2) << '\n';
std::cout << p[0][0] << " " << p[0][1] << " " << p[0][2] << '\n';
// Second, the pointer is allocated on the heap.
int(**q)[3] = new (int(*)[3]) {p};
// That's what I've got after several trials. But I'm still trying to
// understand how does the access to the array work in the next two lines of code?
std::cout << ***q << " " << ***q + 1 << " " << ***q + 2 << '\n';
std::cout << q[0][0][0] << " " << q[0][0][1] << " " << q[0][0][2] << '\n';
}
的代碼打印
10 11 12
10 11 12
10 11 12
10 11 12
編輯 @ A.S.H。在我的代碼中發現了一個錯誤,在他的評論如下。我正在進行必要的更改以澄清示例。
#include <iostream>
int main()
{
// First, pointer p to an array of 3 int's in the stack.
int a[3] = { 100, 200, 300 };
int(*p)[3] = &a;
std::cout << **p << " " << *(*p + 1) << " " << *(*p + 2) << '\n'; // Change here
std::cout << p[0][0] << " " << p[0][1] << " " << p[0][2] << '\n';
// Second, the pointer is allocated on the heap.
int(**q)[3] = new (int(*)[3]) {p};
std::cout << ***q << " " << *(**q + 1) << " " << *(**q + 2) << '\n'; // Change here
std::cout << q[0][0][0] << " " << q[0][0][1] << " " << q[0][0][2] << '\n';
}
由於這些變化,代碼更加清晰。如果我以前知道這個錯誤,我不會提出這個問題。謝謝@ A.S.H。爲您的輸入。
嘗試'int a [3] = {100,200,300};'並再次檢查結果;) –
暗示這是多麼重要:自1980年以來,我一直在專業編程,並從未使用' *** q'或'q [0] [0] [2]'。請花時間學習一些有用的東西! –
@ A.S.H我明白你的意思。看到我上面的編輯。感謝您的提示。 –