[英]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.