0

I have a problem with understanding arithmetic on void pointers,suppose we have this pointer:

int x = 10;
int* p = &x;

so if we want get the address of x we printf p and if we wanna get the value of that address we just printf *p so everything is okay till now, but when i saw this example:

#include<stdio.h>
int main()
{
    int a[2] = {1, 2};
    void *ptr = &a;
    ptr = ptr + sizeof(int);
    printf("%d", *(int *)ptr);
    return 0;
}

the result of the program is 2 and i dont know why ?

why not the program prints zero as a result , because this line means:

ptr = ptr + sizeof(int);

new address of(ptr) = the current address of(ptr) + 4(size of int)

and the value of void pointer is 1 so the shift will be x[5] and its not exist and it must print 0 as a result, why it prints 2 ?

this is the page that i get the example from :

https://www.geeksforgeeks.org/void-pointer-c-cpp/

LEarn123
  • 53
  • 4
  • void pointer arithmetic doesn't really make sense. GeeksForGeeks is not a good reference for C or C++, don't trust what you see there. – Mat Oct 08 '22 at 10:45
  • @Mat , could you give me a good reference for C ? site or book ? – LEarn123 Oct 08 '22 at 11:25
  • 1
    Allowing arithmetic on void pointers is a controversial, nonstandard extension. If you 're thinking in assembly language, where pointers are just addresses, arithmetic on void pointers makes sense, and adding 1 just adds 1. But if you're thinking in C terms, using C's model of pointer arithmetic, adding 1 to any pointer `p` actually adds `sizeof(*p)` to the address, and this is what you want pointer arithmetic to do, but since `sizeof(void)` is 0, it breaks down. If you're thinking in C terms you don't mind, but if you're thinking in assembler you want it to work, thus the extension. – Steve Summit Oct 08 '22 at 12:01

0 Answers0