1

In the following program,if I add 1 to a void pointer, it moves one byte ahead.But,quite as expected, it moves 4 and 8 bytes respectively for int and double pointers.Why does the void pointer move by 1 byte,just as a character pointer would?

#include<stdio.h>

int main(void)
{

        int num=3,*int_ptr=&num;
        double sum=3,*double_ptr=&sum;
        void *void_ptr1=&num,*void_ptr2=&sum;
        printf("%p,%p,%p,%p,%p,%p,%p,%p",void_ptr1,void_ptr1+1,\
        void_ptr2,void_ptr2+1,int_ptr,int_ptr+1,double_ptr,double_ptr+1);
}
Thokchom
  • 1,602
  • 3
  • 17
  • 32
  • 1
    The duplicate points out that pointer arithmetic on `void*` is illegal. Treating it as `char*` arithmetic is a GCC extension. – Pascal Cuoq May 02 '13 at 11:23
  • 1
    @unwind in C99 (§5.1.2.2.3) no return from main is equivalent to `return 0;` while in ANSI C "the termination status returned to the host environment is unspecified" (this is not undefined behaviour, but the return value can be anything) – msam May 02 '13 at 12:44
  • @unwind Unwind,please contradict or second MSAM's statement.It's hard to assume you are wrong given you have a 100k reputation.But then,MSAM made a statement I have heard from many others. – Thokchom May 02 '13 at 13:01

3 Answers3

6

You can't do pointer arithmetic on a void pointer (because it doesn't make sense). Probably it's just that your compiler has an extension that allows pointer arithmetic to be performed on void pointers, and it's implemented like this. However, it is neither standard nor encouraged to be used.

  • 1
    **You can't do pointer arithmetic on a void pointer ** That settles it.Thanks. – Thokchom May 02 '13 at 11:24
  • 2
    The C standard is bordered by an open field, not by a wall. If you were imprisoned, it would be true that you cannot leave. If you live in a town, you can leave, but the town laws do not apply when you do. Thus, it is incorrect so say “You can’t do arithmetic on a void pointer.” A correct statement is “The C standard does not define arithmetic on a void pointer.” This is important because **the C standard was designed to permit extensions**. – Eric Postpischil May 02 '13 at 11:58
3

Actually, incrementing/decrementing of the void* is undefined behavior, as void* means actually pointer to some type. Compiler doesn't know how should it increment a void* and seems to use the predefined value.

So before the incrementing, you have to cast it to a correct type.

Alex
  • 9,891
  • 11
  • 53
  • 87
0

void* is nothing more than a datatype like unsigned int or DWORD. The datatype void* just reminds us that the value it holds is an address. Any arithmetic(those which are allowed) done on void* is similar to that done on unsigned int or DWORD.

raj raj
  • 1,932
  • 1
  • 14
  • 15