sizeof
operand will evaluate the the operand if it is a variable-length array.
6.5.3.4, p2: If the type of the operand is a variable length array type, the operand is evaluated;
Yet this code is working, and I'm assuming it is defined:
#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;
}
- Is the code defined?
- Is the
sizeof
operand evaluated? - Shouldn't evaluation dereference the pointer?
- What is the difference between the first and second
printf
, given the context?
The program seems to be correct with any amount of additional deferences:
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;
}