Not casting pointers in C can cause problems?

前端 未结 6 1815
梦谈多话
梦谈多话 2021-02-07 15:21

Yesterday I was in class, and at some point the instructor was talking about C code. He said:

What is the purpose of making a pointer cast in C? The only

6条回答
  •  忘掉有多难
    2021-02-07 15:49

    What your instructor said about all pointer types sharing the same representation is generally true for real-life implementations of C language.

    However, it is not true from the point of view of abstract C language itself. C language guarantees that

    1. char * pointers are represented in the same way as void * pointers.
    2. Pointers to a qualified version of type T (const, volatile, restrict) are represented in the same way as pointers to unqualified T.
    3. Pointers to all struct types are represented identically.
    4. Pointers to all union types are represented identically.

    That is all. No other guarantees exist. Which means that as far as the language itself is concerned, int * pointer has different representation from double * pointer. And pointer to struct S is represented differently from pointer to union U.

    However, your example with char_pointer and int_pointer, as presented, is not exactly illustrative. The char_pointer = int_pointer; assignment is simply invalid (as in "does not compile"). Language does not support implicit conversions between incompatible pointer types. Such conversions always require an explicit cast operator.

提交回复
热议问题