首先,这里是一些代码:
int main()
{
int days[] = {1,2,3,4,5};
int *ptr = days;
printf("%u\n", sizeof(days));
printf("%u\n", sizeof(ptr));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
有没有办法找出ptr指向的数组的大小(而不是仅仅给出它的大小,在32位系统上是4个字节)?
我不明白为什么sizeof运营商产生以下结果:
sizeof( 2500000000 ) // => 8 (8 bytes).
Run Code Online (Sandbox Code Playgroud)
...它返回8,当我执行以下操作时:
sizeof( 1250000000 * 2 ) // => 4 (4 bytes).
Run Code Online (Sandbox Code Playgroud)
...它返回4而不是8(这是我的预期).有人可以澄清如何sizeof确定表达式(或数据类型)的大小以及为什么在我的特定情况下会发生这种情况?
我最好的猜测是sizeof运算符是编译时运算符.
赏金问题:是否有运行时运算符可以评估这些表达式并产生我的预期输出(没有强制转换)?
我的代码如下:
main() {
int array[5] = {3,6,9,-8,1};
printf("the size of the array is %d\n", sizeof(array));
printf("the address of array is %p\n", array);
printf("the address of array is %p\n", &array);
int * x = array;
printf("the address of x is %p\n", x);
printf("the size of x is %d\n", sizeof(x));
}
Run Code Online (Sandbox Code Playgroud)
输出是
the size of the array is 20
the address of array is 0x7fff02309560
the address of array is 0x7fff02309560
the address of x is 0x7fff02309560
the size of x is …Run Code Online (Sandbox Code Playgroud) 以下代码......
int array[] = {17, 18, 19};
printf("Location of array: %p\n", array);
printf(" Value of array: %d\n", *array);
printf(" Size of array: %d bytes\n", sizeof(array));
Run Code Online (Sandbox Code Playgroud)
产生输出
Location of array: 0x7ffd0491c574
Value of array: 17
Size of array: 12 bytes
Run Code Online (Sandbox Code Playgroud)
当我在第二行使用变量数组时,它指的是"17"的位置.当我在第三个上使用它时,它取消引用指针并打印出数字17.这些,我理解.
在最后一行,它打印出"12字节"作为数组的大小.为什么不打印出4个字节,因为在前两个使用同一个变量时,它似乎只能引用数组的零索引?如何sizeof知道查看数组的其余部分,而不是只打印4个字节(就像我运行时那样(sizeof(*array))?
假设我们有一个数组
int arr[3];
Run Code Online (Sandbox Code Playgroud)
在C++11中我们可以做
end(arr);
Run Code Online (Sandbox Code Playgroud)
得到 arr 的边界。
和
sizeof(arr)/sizeof(arr[0])
Run Code Online (Sandbox Code Playgroud)
可以得到数组的大小。
实际上,我来自 Java,并且是 C++ 新手,拥有某些东西很直观。就像arr.length,但是为什么 C++ 没有这个好功能呢?使用外部函数来获取数组的大小是很奇怪的。(C++11之后甚至添加了结束函数,在此之前事情更麻烦)我猜它有什么。为了处理数组后面的实现,必须有一些边界标记,就像字符串末尾的“\0”一样。那么为什么不更进一步去获得某物呢?像arr.length?