铸造一个int指针为char PTR,反之亦然 [英] Casting an int pointer to a char ptr and vice versa

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

问题描述

问题是简单的。据我了解,海湾合作委员会认为,字符将字节对齐,并在32位环境整数4字节对齐。我也知道C99标准6.3.2.3它说,不对齐指针类型之间铸造导致不确定的操作。做C的其他标准说这是什么?也有许多经验丰富的codeRS在这里 - 有这方面的看法将是AP preciated

 为int * iptr1,* iptr2;
字符* cptr1,* cptr2;iptr1 =(INT *)cptr1;
cptr2 =(字符*)iptr2;


解决方案

有只有一个C标准(一个通过ISO),有两个版本(1989年和1999年),再加上一些pretty小的修改。所有版本和修订同意以下内容:


  • 所有的数据存储器是字节寻址,而字符是字节

  • 因而的char * 将能够解决任何数据

    • 无效* 相同的char * 除了转换和从它不需要类型转换


  • 为int * 转换为的char * 总是工作一样,convering回为int *

  • 任意的char * 转换为为int * 是不能保证工作

字符指针都保证着这样工作的原因是为了让你可以,例如,从任何地方在内存中拷贝整数别处在内存或磁盘,而回,这原来是一个pretty有用的东西在低层次的编程做,例如,图形库。

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;

解决方案

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.

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

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