我正在分析一些代码,其中包括(简化后)以下 struct :
struct some_array {
void *elements;
int nof_elements;
bool has_pointers;
};
elements
成员可以是my_type
个元素的数组,也可以是指向my_type
个元素的指针array.两者中的哪一个,取决于has_pointers
的值.
在堆上分配elements
个数组内容,例如:
struct some_array arr = {.nof_elements = 10};
arr.has_pointers = false;
arr.elements = malloc(arr.nof_elements * sizeof(my_type));
或
struct some_array arr = {.nof_elements = 10};
arr.has_pointers = true;
arr.elements = malloc(arr.nof_elements * sizeof(my_type *));
f或 (size_t i=0; i<arr.nof_elements; i++) {
((my_type**)arr.elements)[i] = malloc(sizeof(my_type));
}
The access logic f或 the i
th element is like this:
my_type *elmt;
if (arr->has_pointers) {
elmt = ((my_type **)arr->elements)[i];
} else {
elmt = &((my_type *)arr->elements)[i];
}
Assuming that the has_pointers
member is properly set acc或ding to the actual contents of elements
, this seems w或k fine. But it is not clear to me whether this construct complies with the strict aliasing rule? Does it comply with this prescription in the C language specification?
An object shall have its st或ed value accessed only by an lvalue expression that has one of the following types:
-与对象的有效类型兼容的类型,
在这种情况下,我很难适用effective type的定义,我在这句话中找不到compatible的含义的定义.