Tan*_*llo 7 c++ pointers internal-representation abstract-machine
在 x86_64 架构上,一个指针是 8 个字节。对我来说sizeof(x)应该返回 8是有意义的。我知道 achar是单个字节,而 5 个字节是 array 的大小z。为什么sizeof(z)不返回8背后的直觉是什么?
int* x = new int[10];
char z[5];
// Returns 8
std::cout << "This is the size of x: " << sizeof(x) << std::endl;
// Returns 5
std::cout << "This is the size of z: " << sizeof(z) << std::endl;
Run Code Online (Sandbox Code Playgroud)
sizeof(z)为什么不返回 8背后的直觉是什么?
z不是指针。因此sizeof(z)不是任何东西,而是 5 个字节。在 的情况下sizeof,数组不会衰减为指针。参考:什么是数组衰减?
C++ 中有多种隐式转换,如数组到指针、枚举到整数、double到float、派生到基数、任何指针void*等等。这可能会让我们思考它们的大小是否相同或者是什么?
因此,自我理解的试金石是创建一个指针引用并尝试分配其他类型。它会导致不匹配类型的错误。例如
int *x = new int[5], *&px = x; // OK
int z[5], *&pz = z; // error: can't initialize
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
121 次 |
| 最近记录: |