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

后端 未结 3 2696
别跟我提以往
别跟我提以往 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条回答
  •  清歌不尽
    2021-02-20 18:49

    *ptr = 0;
    

    writes to an int, so it is an access to int, with an lvalue of type int, so that part of the code is fine.

    The cast is morally fine, but the C/C++ standard texts don't clearly describe casts, or pointers, or anything fundamental.

提交回复
热议问题