Can I do arithmetic on void * pointers in C?

后端 未结 6 559
攒了一身酷
攒了一身酷 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:17

    To quote from the spec:

    §6.5.6/2: For addition, either both operands shall have arithmetic type, or one operand shall be a pointer to an object type and the other shall have integer type. (Incrementing is equivalent to adding 1.)

    A pointer to void is not a pointer to an object type, as per these excerpts:

    §6.2.5/1: [...] Types are partitioned into object types (types that fully describe objects), function types (types that describe functions), and incomplete types (types that describe objects but lack information needed to determine their sizes).

    §6.2.5/19: The void type comprises an empty set of values; it is an incomplete type that cannot be completed.

    Therefore, pointer arithmetic is not defined for pointer to void types.

提交回复
热议问题