Is it legal to alias a char array through a pointer to int?

后端 未结 3 2683
别跟我提以往
别跟我提以往 2021-02-20 17:57

I know that the following is explicitly allowed in the standard:

int n = 0;
char *ptr = (char *) &n;
cout << *ptr;

What about this?

3条回答
  •  旧时难觅i
    2021-02-20 18:54

    The union construct might be useful here.

    union is similar to struct, except that all of the elements of a union occupy the same area of storage.

    They are, in other words, "different ways to view the same thing," just like FORTRAN's EQUIVALENCE declaration. Thus, for instance:

    union {
      int   foo;
      float bar;
      char  bletch[8];
    }
    

    offers three entirely-different ways to consider the same area of storage. (The storage-size of a union is the size of its longest component.) foo, bar, and bletch are all synonyms for the same storage.

    union is often used with typedef, as illustrated in this StackOverflow article: C: typedef union.

提交回复
热议问题