【发布时间】:2015-11-12 07:46:00
【问题描述】:
sizeof 操作数将计算操作数,如果它是一个变长数组。
6.5.3.4、p2:如果操作数的类型是变长数组类型,则对操作数求值;
但这段代码正在运行,我假设它已定义:
#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;
}
- 代码定义了吗?
- 是否评估了
sizeof操作数? - 评估不应该取消对指针的引用吗?
- 根据上下文,第一个和第二个
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;
}
【问题讨论】:
-
但是显示的操作数类型是
int。没有? -
我认为该声明的意思是,如果您执行
sizeof(a),则评估a[r]。即需要获取r的实际值。但我不是语言专家,所以如果不是这个意思,请纠正。 -
@bleakgadfly 不是重复的,因为它不直接处理 VLA。
标签: c language-lawyer c99 c11 variable-length-array