Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Garbage value while incrementing a 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 value but I was expecting it to print 2. Why doesn't it print 2?

like image 474
Pointeratfb.com Avatar asked Jul 17 '26 06:07

Pointeratfb.com


2 Answers

You can't perform pointer arithmetic on a void pointer because the compiler doesn't have any idea about the size of the pointed to objects.

Your code doesn't get compiled on comeau online. Its another evil gcc extension I guess.

like image 92
Prasoon Saurav Avatar answered Jul 18 '26 20:07

Prasoon Saurav


Some C compilers treat void pointer arithmetic as they do char*. It's invalid in C++.

No matter, you really should only be incrementing non void pointers since pointer arithmetic relies on knowledge of the size and alignment of the data type.

like image 30
David Heffernan Avatar answered Jul 18 '26 19:07

David Heffernan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!