gpt4 book ai didi

c - 适用于 char 字符串的别名规则

转载 作者:行者123 更新时间:2023-11-30 17:33:57 25 4
gpt4 key购买 nike

我不明白为什么这段代码会触发别名警告:

char buf[15];

*(uint16_t*) buf = 0x4040;

char 类型中没有任何可以想象的“对齐方式”。无论如何,我该如何以优雅的方式做到这一点?到目前为止我想不出比这更好的了

char buf[15];
uint16_t foo = 0x4040;
memcpy(buf, &foo, 2);

警告是这样的:

warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing]

最佳答案

There is no any thinkable "alignments" within char type.

这就是问题所在,字符数组通常具有尽可能小的对齐要求,即 1。

但是,您的代码尝试将其视为 uint16_t,它可能具有与 1(通常为 2)不同的对齐要求。

您这里的解决方案是合理的:

char buf[15];
uint16_t foo = 0x1234; //changed this to demonstrate endian issue
memcpy(buf, &foo, 2);

这两种方法的警告是 buf 的内容将取决于主机的字节序,即你最终会得到一个小端系统

buf[0] == 0x34;
buf[1] == 0x12;

在大端系统上,值将颠倒。如果这不是问题,那么一切都很好。如果这是一个问题,您可以这样做,而不是 memcpy():

 buf[0] = foo & 0xff;
buf[1] = foo >> 8;

关于c - 适用于 char 字符串的别名规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23571058/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com