将 int 指针转换为 char ptr,反之亦然
问题很简单。据我了解,GCC 认为在 32 位环境中,字符将按字节对齐,整数将按 4 字节对齐。我还知道 C99 标准 6.3.2.3 规定,未对齐的指针类型之间的转换会导致未定义的操作。 C 的其他标准对此有何评论?这里还有许多经验丰富的编码员 - 任何对此的看法都将受到赞赏。
int *iptr1, *iptr2;
char *cptr1, *cptr2;
iptr1 = (int *) cptr1;
cptr2 = (char *) iptr2;
The problem is simple. As I understand, GCC maintains that chars will be byte-aligned and ints 4-byte-aligned in a 32-bit environment. I am also aware of C99 standard 6.3.2.3 which says that casting between misaligned pointer-types results in undefined operations. What do the other standards of C say about this? There are also many experienced coders here - any view on this will be appreciated.
int *iptr1, *iptr2;
char *cptr1, *cptr2;
iptr1 = (int *) cptr1;
cptr2 = (char *) iptr2;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
C 语言只有一个标准(ISO 标准),有两个版本(1989 年和 1999 年),以及一些相当小的修订。所有版本和修订都同意以下内容:
char*
将能够寻址任何数据void*
与char*
相同,只是与它之间的转换不需要类型转换int*
到int*
的类型转换。 code>char* 始终有效,就像转换回int*
一样,char*
转换为int*
char 指针保证像这样工作的原因是,例如,您可以将整数从内存中的任何位置复制到内存或磁盘中的其他位置,然后再复制回来,这在低功耗环境中是非常有用的。级编程,例如图形库。
There is only one standard for C (the one by ISO), with two versions (1989 and 1999), plus some pretty minor revisions. All versions and revisions agree on the following:
char*
will be able to address any datavoid*
is the same aschar*
except conversions to and from it do not require type castsint*
tochar*
always works, as does convering back toint*
char*
toint*
is not guaranteed to workThe reasons char pointers are guaranteed to work like this is so that you can, for example, copy integers from anywhere in memory to elsewhere in memory or disk, and back, which turns out to be a pretty useful thing to do in low-level programming, e.g., graphics libraries.
CPU有big-endian和little-endian之分,所以结果是不确定的。
例如,对于 char 指针,转换后 0x01234567 的值可能是 0x12 或 0x67。
There are big-endian and little-endian for CPUs, so the results are undefined.
For example, the value of 0x01234567 could be 0x12 or 0x67 for a char pointer after casting.
你可以尝试这样做:
这对我在 DevCpp 有用!
You can try doing:
This worked for me in DevCpp!