gpt4 book ai didi

c - 可变长度数组的 sizeof 计算

转载 作者:太空宇宙 更新时间:2023-11-04 01:02:47 25 4
gpt4 key购买 nike

sizeof 操作数将评估操作数是否为可变长度数组。

6.5.3.4, p2: If the type of the operand is a variable length array type, the operand is evaluated;

然而这段代码是有效的,我假设它已被定义:

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

struct test
{
struct test* t;
int i;
};

int main(void)
{
int r = ( rand() % 100 ) + 1;
assert( r > 0 );
struct test* a[r];
for( size_t i = 0; i < r; i++ )
{
a[i] = NULL;
}

printf("%zu\n" , sizeof( a[0]->i ) );
//printf("%d\n", a[0]->i ); //this will of course crash the program

return 0;
}
  1. 是否定义了代码?
  2. 是否计算了 sizeof 操作数?
  3. 评估不应该取消对指针的引用吗?
  4. 在给定上下文的情况下,第一个和第二个 printf 有什么区别?

该程序似乎是正确的,具有任何数量的额外尊重:

struct other
{
int i;
};

struct test
{
struct other* t;
};

int main(void)
{
int r = ( rand() % 100 ) + 1;
assert( r > 0 );
struct test* a[r];
for( size_t i = 0; i < r; i++ )
{
a[i] = NULL;
}

printf("%zu\n" , sizeof( a[0]->t->i ) );
//printf("%d\n", a[0]->t->i ); //this will of course crash the program

return 0;
}

最佳答案

a 本身就是一个 VLA。但是a[0]->i不是,它的类型是int

所以 sizeof( a[0]->i ) 就是 sizeof(int)sizeof 这里是一个编译时操作符,a[0]->i 没有被求值,代码被定义。

关于c - 可变长度数组的 sizeof 计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32088226/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com