Casting an int pointer to a char ptr and vice vers

2019-01-17 16:29发布

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;

3条回答
欢心
2楼-- · 2019-01-17 17:12

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.

查看更多
Evening l夕情丶
3楼-- · 2019-01-17 17:18

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!

查看更多
够拽才男人
4楼-- · 2019-01-17 17:31

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.

查看更多
登录 后发表回答