Can I do arithmetic on void * pointers in C?

后端 未结 6 552
攒了一身酷
攒了一身酷 2020-12-03 14:45

is this valid

void *p = &X; /* some thing */
p += 12;

and if so what does p now point to? I have (third party) code that does this (an

6条回答
  •  既然无缘
    2020-12-03 15:11

    No this is not legal. A void* cannot be arbitrarily incremented. It needs to be cast to a specific type first.

    If you want to increment it by a specific number of bytes then this is the solution I use.

    p = ((char*)p) + 12;
    

    The char type is convenient because it has a defined size of 1 byte.

    EDIT

    It's interesting that it runs on gcc with a warning. I tested on Visual Studio 2010 and verified it does not compile. My limited understanding of the standard would say that gcc in the error here. Can you add the following compilation flags

    -Wall -ansi -pedantic
    

提交回复
热议问题