Sumit Trehan
Sumit Trehan

Reputation: 4035

Operation on void pointer

It is known that void pointer airthmetic is invalid.

int main {
    int b = 10;
    void *a = (void *) &b;
    void *c = a + 1;
    printf ("%p\n", a);
    printf ("%p\n", c);
}

    Output:
     0x7fff32941d1c             
     0x7fff32941d1d

I have read that above airthmetic is unexpected behaviour and we cannot rely on it.

Now moving on to actual question. I am taking an array of void pointers.

int main()
{
    void *a[10];
    void **b = a;
    void **c = (a + 1);
    printf ("%p\n", b);
    printf ("%p\n", c);
}

Output:
0x7fff8824e050          
0x7fff8824e058

Can you please explain the above behavior, where a double pointer (pointer to a void pointer is used). Is it expected behavior?

Upvotes: 2

Views: 404

Answers (1)

R Sahu
R Sahu

Reputation: 206567

Can you please explain the above behavior, where a double pointer (pointer to a void pointer is used). Is it expected behavior?

Yes, it is expected behavior.

That's because the size of the object the pointer points to is known. It is sizeof(void*).

If the values of the pointers are expressed in purely integral values,

(a + 1) == a + 1*sizeof(void*)

It appears that on your platform, sizeof(void*) is 8.

Upvotes: 6

Related Questions