How does pointer arithmetic - specifically, addition with numbers - work if the pointer points to a multidimensional array?
When I debugged the sample program below:
int main(void) {
int a[3][4] = {{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}};
int *p1 = a;
// set breakpoint ...
...
}
If I use debugger (CLion) to print *(p1 + N), it gives me an array having (N + 1) elements, starting from element a[N / col_size][N % col_size]. This doesn't match my expectation. Listing actual result and expectation as below:
| Enter into debugger to print | Debugger result | Expectation |
|---|---|---|
*(p1) |
{1} |
{1, 2, 3, 4} |
*(p1 + 2) |
{3, 4, 5} |
{9, 10, 11, 12} |
*(p1 + 5) |
{6, 7, 8, 9, 10, 11} |
{an array of random numbers} |
*(p1 + 6) |
{7, 8, 9, 10, 11, 12, -11}. -11 is random as it already exceeded the allocated size of the array. |
{an array of random numbers} |
I understand that C stores multidimensional array in row-major order, but what confuses me is why does C provide an array of (N + 1) length for *(p1 + N)?