Search code examples
c++arraysvoid-pointerspointer-arithmetic

You can't use pointer arithmetic on void pointers, so how do arrays of void pointers work?


From reading tutorials, my understanding is that behind the scenes the operator([]) does the same thing as pointer arithmetic.

Learncpp has the following to say "It turns out that when the compiler sees the subscript operator ([]), it actually translates that into a pointer addition and dereference!".

Wikibooks then says this "A variable declared as an array of some type acts as a pointer to that type. When used by itself, it points to the first element of the array."

Then after reading about void pointers, I was curious to know how would an array of them work? I imagine that my understanding of something must be wrong.

For an example the following two should be identical.

a)

void* array[5];
array[1] = nullptr;

b)

void* array[5];
*(array + 1) = nullptr;

Solution

  • An array of pointers is basically just ** - void** in your case.

    You know the size of void* as it's just another pointer.