Pointer arithmetic for void pointer in C

前端 未结 8 1254
执念已碎
执念已碎 2020-11-22 01:23

When a pointer to a particular type (say int, char, float, ..) is incremented, its value is increased by the size of that data type. I

8条回答
  •  情书的邮戳
    2020-11-22 01:50

    Compiler knows by type cast. Given a void *x:

    • x+1 adds one byte to x, pointer goes to byte x+1
    • (int*)x+1 adds sizeof(int) bytes, pointer goes to byte x + sizeof(int)
    • (float*)x+1 addres sizeof(float) bytes, etc.

    Althought the first item is not portable and is against the Galateo of C/C++, it is nevertheless C-language-correct, meaning it will compile to something on most compilers possibly necessitating an appropriate flag (like -Wpointer-arith)

提交回复
热议问题