问题描述
请参见以下代码:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int arr[10];
int *arr2;
arr2=malloc(10*sizeof(int));
printf("The size of arr is %lu \n",sizeof(arr));
printf("The sice of arr2 is %lu \n",sizeof(arr2));
return 0;
}
输出为:
The size of arr is 40
The sice of arr2 is 8
我知道arr
包含数组中第一个元素的地址。
我的问题是:为什么sizeof()
运算符对arr
返回40,对arr2
返回8?
sizeof(arr)
为何是40,因为它仅存储数组的第一个元素的地址?
解决方法
arr
不包含数组第一个元素的地址。 arr
是数组。在大多数情况下,它只是衰减为指向第一个元素的指针。
当数组名称是sizeof
运算符的主题时,数组名称不会衰减的几次。在这种情况下,sizeof
会得出数组大小(以字节为单位),在这种情况下为40。
arr2
是指向int
的指针,因此在其上使用sizeof
可以得到系统上的指针大小为8。它不是它是否指向动态分配的数组,本地数组的开始或两者之中的某个位置无关紧要。 sizeof
唯一要看的是其操作数的类型。实际上,除非其操作数是可变长度数组,否则sizeof
会被评估为编译时间。
因为您所用的类型不同(int [10]与int *)。如果您保留相同的类型,则两者将返回相同的数字。
Nit:代替zu,使用zu打印size_t。
道德:sizeof不是函数,而是运算符。
, sizeof
是一个运算符,其大小可以在编译时解析。编译器不知道malloc
将返回什么。它只会看到类型int arr[10];
和int *arr;
并返回当前平台上类型的大小