在使用指针算法时offsetof,是否采用了良好定义的行为来获取结构的地址,向其添加成员的偏移量,然后取消引用该地址以获取基础成员?
请考虑以下示例:
#include <stddef.h>
#include <stdio.h>
typedef struct {
const char* a;
const char* b;
} A;
int main() {
A test[3] = {
{.a = "Hello", .b = "there."},
{.a = "How are", .b = "you?"},
{.a = "I\'m", .b = "fine."}};
for (size_t i = 0; i < 3; ++i) {
char* ptr = (char*) &test[i];
ptr += offsetof(A, b);
printf("%s\n", *(char**)ptr);
}
}
Run Code Online (Sandbox Code Playgroud)
这应该打印"那里","你呢?" 并且"很好".连续三行,它目前与clang和gcc一起使用,因为你可以在wandbox上验证自己.但是,我不确定这些指针强制转换和算术是否违反某些规则会导致行为变为未定义.