#include<stdio.h>
int main(int argc,char *argv[])
{
int i=10;
void *k;
k=&i;
k++;
printf("%p\n%p\n",&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++.
It is a GCC extension.
If you add the
-pedanticflag it will produce the warning:If you want to abide to the standard, cast the pointer to a
char*:The standard specifies one cannot perform addition (
k+1) onvoid*, because:Pointer arithmetic is done by treating
kas the pointer to the first element (#0) of an array ofvoid(C99 §6.5.6/7), andk+1will return element #1 in this “array” (§6.5.6/8).For this to make sense, we need to consider an array of
void. The relevant info forvoidis (§6.2.5/19)However, the definition of array requires the element type cannot be incomplete (§6.2.5/20, footnote 36)
Hence
k+1cannot be a valid expression.