将 int 指针转换为 char ptr,反之亦然

发布于 2024-10-04 15:32:02 字数 262 浏览 7 评论 0原文

问题很简单。据我了解,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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

音栖息无 2024-10-11 15:32:02

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:

  • 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
  • converting from int* to char* always works, as does convering back to int*
  • converting an arbitrary char* to int* is not guaranteed to work

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.

伴梦长久 2024-10-11 15:32:02

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.

梦毁影碎の 2024-10-11 15:32:02

你可以尝试这样做:

iptr1 = atoi(cptr1); // val now = pointed by cptr1
cptr2 = atoi(iptr2); // val now = pointed by iptr2

这对我在 DevCpp 有用!

You can try doing:

iptr1 = atoi(cptr1); // val now = pointed by cptr1
cptr2 = atoi(iptr2); // val now = pointed by iptr2

This worked for me in DevCpp!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文