I have the following code:
int main() {
int n = 3, m = 4, a[n][m], i, j, (* p)[m] = a;
for (i = 0; i < n; i++)
for (j = 0; j < m; j++)
a[i][j] = 1;
p++;
(*p)[2] = 9;
return 0;
}
I have a hard time understanding what p is here, and the consequences of the operations on p in the end. Can someone give me a brief explanation of what happens. I know c-pointers in their simple settings, but here it get slightly more complicated.
ais an array ofint[m], andpis a pointer toint[m]. It’s initialized toa, which decays to a pointer to its first element.Dereferencing
pyieldsint[m], which decays toint*(pointer to its first element). So(*p)[2]adds2to theint*that was the result of the decay. So it’s setting the third of the first4integers (int[m], withmbeing 4) to9.Adding to
pwould advance the address stored in it by units ofsizeof(int[m])bytes, which at runtime (sincemis not a compile time constant) evaluates to4 * sizeof(int). So(*(p+1))[2]would access the third of the second4integers. In total,phas3such arrays of4ints to point to:a+0,a+1anda+2.Notice that you created a C99 VLA, variable length array. You need to
#definenandmto integer constants to get rid of those VLAs (which aren’t quite portable among C compilers).