The value of garbage when increasing void *

This code:

#include <stdio.h>
int main(void)
{
   void *ptr;
   int arr[] = {1,2,3,4,5};
   ptr = arr;
   ptr++;
   printf("%d",*(int*)ptr);
}

Prints some garbage cost, but I expected it to print 2. Why doesn't he print 2?

+3
source share
3 answers

Some C compilers handle void pointer arithmetic as they do char *. It is not valid in C ++.

Regardless, you really should only increment non-empty pointers, since pointer arithmetic is based on knowing the size and alignment of the data type.

+4
source

You cannot do pointer arithmetic on a void pointer because the compiler has no idea about the size of objects pointing to objects.

-. gcc, .

+5

int *ptr

ptr ++ int

-2

All Articles