为什么sizeof在未设置元素时返回值?

use*_*471 1 c

#include <stdio.h>

int main(void) {

int TEST_HB[10]; 
memset(TEST_HB,'9', sizeof( TEST_HB));

printf("%c\n",TEST_HB[9]);

printf ("TEST_HB[10]=%d\n",sizeof( TEST_HB[40]));   // shows 4
printf ("Arraysize=%d\n",(sizeof(int)*10));     // gets the expectected results
return 0;

} 
Run Code Online (Sandbox Code Playgroud)

我相信sizeof(myArray)应该以字节为单位返回数组的总大小.但是,为什么sizeof( TEST_HB[40])在没有定义时会返回4?

Ste*_*sop 7

TEST_HB[40]是一个带有类型的表达式int(如果计算,40则为未定义的行为,因为对于数组来说太大了).实现sizeof(TEST_HB[40])的大小也是如此int:4是典型的.

重要的是,sizeof除非它是VLA,否则不评估其操作数 - 它只使用该类型.因此,即使没有这样的对象,您的代码也已定义了行为TEST_HB[40].

实际上,我说它已经定义了行为,但是sizeof评估了类型size_t,它没有打印出来%d.请%zu在可用的地方使用或参考编译器文档.你已经离开了它,因为你已经很幸运了varargs调用约定,加上或者你的实现中的size_t大小相同int,或者你的实现是little-endian,或两者兼而有之.

sizeof不评估操作数的事实的一个相当普遍的用法是写这样的东西:

struct Foo *foo = malloc(sizeof(*foo) * number_of_foos_required);
Run Code Online (Sandbox Code Playgroud)

sizeof(*foo)是一样的sizeof(struct Foo),但对某些人来说,它"更明显"使用的尺寸更合适.foo在分配内存之前是未初始化的,所以它sizeof实际上并没有实际使用的值foo.

一种较不常见的用法,它表明了以下行为sizeof:

int i = 0;
printf("%d\n", i);
printf("%d\n", (int)(sizeof(i++))); // i++ is not executed
printf("%d\n", i);
Run Code Online (Sandbox Code Playgroud)