【发布时间】:2021-11-04 18:47:25
【问题描述】:
我对 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 ]
上面的代码会调用未定义的行为吗?
我在网上搜索,发现大多数关于聚合类型和有效类型的讨论都涉及结构指针,而不是指向数组的指针。即便如此,对于设置单个结构成员是否只为该成员或该结构将包含的整个内存块赋予有效类型似乎存在分歧和困惑。
【问题讨论】:
-
关于“这方面的标准是否明确?”:没有。
-
想象一下将所有双精度数据存储在一个特殊内存池中的计算机,该内存池只能由 FPU 访问。 FPU 无法访问普通内存。从/到“普通内存”的传输需要特殊的机器代码指令。你的指针双关会起作用吗?
-
@0___________ 考虑到函数必须返回适合与 any 类型一起使用的 连续 内存,这样的计算机能否首先提供 malloc?如果是这样,并且计算机因此可以决定在分配后的某个时间为 malloced 块的某些段使用特殊内存,那么我认为您的问题本质上与我要问的问题相同:是否通过指向一个成员的指针访问一个成员聚合类型允许编译器对所有其他成员和/或整个块进行类型假设?
标签: c pointers language-lawyer pointer-to-array