在 C 中指向数组的指针的情况下,我对有效类型感到困惑。通过指向数组的指针访问单个成员是否仅在该成员的内存或数组包含的所有内存上赋予有效类型?标准在这方面是否明确?
int ( *foo )[ 10 ] = malloc( sizeof( *foo ) );
**foo = 123; //Or ( *foo )[ 0 ] = 123
//Is the effective type of the memory for (*foo)[ 0 – 9 ] now also int?
//Does the whole region now have an effective type?
//Or can this memory be used for other purposes?
这是一个实际的例子:
int (*foo)[ 10 ];
double *bar;
//Figure out the size an int padded to comply with double alignment
size_t padded_int_size =
( ( ( sizeof( int ) + alignof( double ) - 1 ) / alignof( double ) ) * alignof( double ) );
//Allocate memory for one padded int and 1000 doubles,
//which will in any case be larger than an array of 10 ints
foo = malloc( padded_int_size + sizeof( double ) * 1000 );
//Set our double pointer to point just after the first int
bar = (double*)( (char*)foo + padded_int_size );
//Do things with ( *foo )[ 0 ] or **foo
//Do things with bar[ 0 - 999 ]
上面的代码会调用未定义的行为吗?
我在网上搜索,发现大多数关于聚合类型和有效类型的讨论都涉及结构指针,而不是指向数组的指针。即便如此,对于设置单个结构成员是否仅对该成员或该结构将包含的整个内存块赋予有效类型似乎存在分歧和混淆。