将指针传递给压缩结构成员时发出警告

Warning when passing pointers to packed structure member

我想将对 packed 结构的引用传递给函数。不幸的是,编译器 (gcc 9.3.0) 不喜欢我的想法并抱怨未对齐的指针。我明白这意味着什么,但我不知道如何解决它。

struct map {  
   ...
   int32_t xy;
   ...
} __attribute__((__packed__));

void Test::write(int32_t* addr, const int32_t &value) {
  int64_t beval = htobe64(value);
  memcpy(addr, &beval, sizeof(beval));
}

int32_t val32 = 123;
write(&map.xy, val32);
warning: taking address of packed member of ‘Test::map’ may result in an unaligned pointer value [-Waddress-of-packed-member]
   xx |     write(&map.xy, val32);
      |           ^~~~~~~~~~~~~~~~

I do not see how to fix it.

要么不获取它的地址,不打包 map,要么接受你的程序可能有未定义的行为。

作为解决方法,您可以使用中间值:

int32_t val32 = 123;
{
    auto aligned_xy = map.xy; // Fix possible alignment "issue"
    write(&aligned_xy , val32);
    map.xy = aligned_xy;
}

注意:write 不应保留 'intermediate' 指针。