0

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;
3
  • 1
    Remember that arrays decays to pointers to their first element. That is, array decays to &array[0]. And that decayed pointer has the type void** which you can do pointer arithmetic on. Commented Jul 7, 2019 at 9:21
  • what is your question? the size of a void pointer is known (architecture specific though....). e.g. 32bit. Thus (array +1) will actually add 4bytes (size of each element if sizeof(void) is 4) to the base address. Commented Jul 7, 2019 at 9:22
  • My question was, how does the operator([]) work with since there seemed to be a contradiction, but the above comment cleared that up. In fact I'd like him to post that as the answer, so I can mark it as correct. Commented Jul 7, 2019 at 9:25

1 Answer 1

2

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

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.