[英]How to assign address of array to pointer?
#include <iostream>
int main() {
int arr[2] = {1, 2};
int *p;
// p = &arr; // Does not compile
p = &arr[0]; // compiles
std::cout << "&arr = " << &arr << std::endl;
std::cout << "&arr[0] = " << &arr[0] << std::endl;
}
當我嘗試打印地址時,兩者都打印相同的地址。 但是當我嘗試分配p = &arr
它不會編譯。 標准中是否有一些內容反對將數組地址分配給指針。 我只是想知道p = &arr
無法編譯的原因?
Clang 實際上說error: cannot initialize a variable of type 'int *' with an rvalue of type
p = &arr;
是編譯器錯誤,因為&arr
的類型是int (*)[2]
-- 指向“2 個int
數組”的指針。 因此,它不能分配給p
,其類型為int*
。
盡管&arr
和&arr[0]
計算為相同的數值,但它們是不同的類型。
所以你有這個:
arr[0] is the first item in memory
arr[1] is the second item in memory
這等效於以下內容:
*((int*)arr + 0) is the first item in memory
*((int*)arr + 1) is the second item in memory
“取消引用”指針,這使您可以訪問所需的內存,而不是在內存中表示它的數字(指針):
*((int*)arr + 0)
這相當於:
arr[0]
如果您想要任何項目的地址,您可以按如下所示執行:
(int*)arr + Index
第一項的地址是數組開頭的內存地址,所以數組和第一項的地址是:
(int*)arr + 0 or just (int*)arr
此處的代碼獲取第一項的地址,該地址與數組的地址相同:
p = &arr[0]; // compiles
每當你放置一個 & 符號時,它就相當於獲取了的地址,所以這里你得到的是 [數組地址的地址],這與 [數組地址] 不同
p = &arr; // Does not compile
數組地址的地址類型為:
int (*)[2];
不是:
int *p;
這就是為什么它不編譯,類型不匹配。
為了幫助解決像這樣的類型相關錯誤,您可以使用 typeid 和 decltype,在 C++ 中,這可以讓您打印相關類型的名稱。
像這樣
#include <iostream>
using namespace std;
int main()
{
int arr[2] = {1, 2};
std::cout<< "typeid ptr_array is " << typeid(decltype(&arr)).name() << "\n";
std::cout<< "typeid ptr_item is " << typeid(decltype(&arr[0])).name() << "\n";
return 0;
}
結果是:
ptr_array is PA2_i (Pointer to Array of size 2 with int)
ptr_item is Pi (Pointer to int)
typeid 中的“P”表示指針,“A”表示數組。
你可以在這里玩自己: https : //wandbox.org/permlink/RNNxjTMSUnLqUo6q
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.