void * arithmetic

坚强是说给别人听的谎言 提交于 2019-11-29 03:01:21

It is a GCC extension.

In GNU C, addition and subtraction operations are supported on pointers to void and on pointers to functions. This is done by treating the size of a void or of a function as 1.

If you add the -pedantic flag it will produce the warning:

warning: wrong type argument to increment

If you want to abide to the standard, cast the pointer to a char*:

k = 1 + (char*)k;

The standard specifies one cannot perform addition (k+1) on void*, because:

  1. Pointer arithmetic is done by treating k as the pointer to the first element (#0) of an array of void (C99 §6.5.6/7), and k+1 will return element #1 in this "array" (§6.5.6/8).

  2. For this to make sense, we need to consider an array of void. The relevant info for void is (§6.2.5/19)

    The void type comprises an empty set of values; it is an incomplete type that cannot be completed.

  3. However, the definition of array requires the element type cannot be incomplete (§6.2.5/20, footnote 36)

    Since object types do not include incomplete types, an array of incomplete type cannot be constructed.

Hence k+1 cannot be a valid expression.

No, arithmetic on void* is not covered by the standard. Use char* for this.

You cannot increment a pointer to void. The compiler does not know what is the sizeof target structure.

The standard requires that all pointer arithmetic operators require the pointer to be to a complete object type. void is an incomplete type. GCC is doing the wrong thing.

Arithmetic on void* is a GCC extension. When I compile your code with clang -Wpointer-arith the output is :

test.c:9:4: warning: use of GNU void* extension [-Wpointer-arith]
k++;
~^

The usual behavior of a pointer increment is to add the size of the pointee type to the pointer value. For instance :


int *p;
char *p2;
p++; /* adds sizeof(int) to p */
p2 += 2; /* adds 2 * sizeof(char) to p2 */

Since void has no size, you shouldn't be able to perform pointer arithmetic on void* pointers, but GNU C allows it.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!