Not casting pointers in C can cause problems?

前端 未结 6 1709
梦谈多话
梦谈多话 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:46

    What your Prof said sounds right.

    ...(for example, adding an int pointer will result in a different offset than adding a char pointer)

    This is true because assuming int is 4 bytes and char is 1 byte, adding a 2 to an int pointer will result in moving the pointer by 8 bytes, whereas adding a 2 to a char pointer will only move the pointer to the next byte 2 positions away.

    Apart from that, there is no difference: all pointers are represented the same way in memory, regardless if the pointer is pointing to an int value, a char value, a short value, or whatever.

    This is true, the machine makes no distinction between char vs int pointers, these are the compiler's issue to deal with. Also as your prof mentioned:

    The only purpose is to make the compiler interpret correctly the pointer operations

    So, casting a pointer will not modify anything in the memory, it will just help the programmer with operations more related with the pointer-type he is dealing with.

    This is again true. Casting does not modify memory, it just changes how a part of memory is interpreted.

提交回复
热议问题