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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With