将 int 指针转换为 char ptr,反之亦然 [英] Casting an int pointer to a char ptr and vice versa

查看:18
本文介绍了将 int 指针转换为 char ptr,反之亦然的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题很简单.据我了解,GCC 认为在 32 位环境中,字符将按字节对齐,整数按 4 字节对齐.我也知道 C99 标准 6.3.2.3 说在未对齐的指针类型之间进行转换会导致未定义的操作.C 的其他标准对此有何看法?这里还有许多经验丰富的编码员 - 对此的任何看法将不胜感激.

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;

推荐答案

C 只有一个标准(ISO 的一个标准),有两个版本(1989 和 1999),还有一些非常小的修订.所有版本和修订均同意以下内容:

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* 将能够寻址任何数据
    • void*char* 相同,只是与它的转换不需要类型转换
    • all data memory is byte-addressable, and chars are bytes
    • thus a char* will be able to address any data
      • void* is the same as char* except conversions to and from it do not require type casts

      char 指针之所以能保证像这样工作的原因是,例如,您可以将整数从内存中的任何地方复制到内存或磁盘中的其他地方,然后再返回,结果证明这是一件非常有用的事情低级编程,例如图形库.

      The 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.

      这篇关于将 int 指针转换为 char ptr,反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆