logoalt Hacker News

quietbritishjimtoday at 10:55 AM1 replyview on HN

> If you see a[i][j] it could mean two completely different things:

> 1) ... a[i][j] == *((char*)a + i*M + j) // I added the char* cast to make it correct

> 2) ... a[i][j] == *(*(a + i) + j)

You may already understand this but: even in case (1), you still have

   a[i][j] = *(*(a + i) + j)
(It has to - that's what operator[] means in C.)

It's just that, in this case, `a + i` is applying pointer arithmetic to char[M]* so it adds M * i bytes to a's address.

This is similar to how `a + i`, if a is int32_t*, will give you an address 4 * i bytes bigger than a.

Really the confusing part of this is that *(a + i), which is an array value i.e. has type char[M], decays to char* when you add an integer to it (or dereference it). This is a pretty crazy hack really. Imagine if, in C++, you could do this

   std::vector<int> v = {1, 2, 3};
   int* x = v + 1;   // equivalent to &v[1]
Yuck.

Replies

quietbritishjimtoday at 2:04 PM

Too late to edit but I wrote pointer to char[M] as char[M]* when, of course(!), it should be written as char(*)[M].