Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
443 views
in Technique[技术] by (71.8m points)

c - void * arithmetic

#include<stdio.h>
int main(int argc,char *argv[])
{
   int i=10;
   void *k;
   k=&i;

   k++;
   printf("%p
%p
",&i,k);
   return 0;
}

Is ++ a legal operation on void* ? Some books say that it's not but K & R doesn't say anything regarding void * arithmetic ( pg. 93,103,120,199 of K &R 2/e)

Please clarify.

PS : GCC doesn't complain at least in k++.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...