问题
I'm trying to understand how to set a column of a two dimensional array to 0.
I follow this code snippet from C programming textbook by K.N. King.
int a[NUM_ROWS][NUM_COLS], (*p)[NUM_COLS], i;
...
for (p = &a[0]; p < &a[NUM_ROWS]; p++)
(*p)[i] = 0;
I genuinely don't understand how this works. Greatly appreciate any clarification.
回答1:
It's all related to how an array is converted to a pointer on access, see: C11 Standard - 6.3.2.1 Other Operands - Lvalues, arrays, and function designators(p3).
In your case you have a two dimensional array of int a[NUM_ROWS][NUM_COLS];. Which in reality is an array of arrays of int[NUM_COLS]. (an array of 1D arrays).
When you access a, a is converted to a pointer to the first 1D array and is of type int (*)[NUM_COLS] (a pointer to an array of NUM_COLS integers).
You declare p as a pointer to an array of NUM_COLS integers, so p is type compatible with a. You can simply initialize:
p = a;
(instead of p = &a[0];)
In your for loop you loop from p = a; (a pointer to the first 1D array), and loop while p is less than &a[NUM_ROWS] (the address 1-after the final 1D array) incrementing p each iteration (and since p is a pointer to int[NUM_COLS], p points to the next row each time you increment p)
When you dereference p you have an array of int[NUM_COLS], so when you address (*p)[i] = 0; you are setting the ith element of that row to 0.
That's it in a nutshell. Let me know if you are still confused and where and I'm happy to try and explain further.
来源:https://stackoverflow.com/questions/58497885/processing-the-columns-of-a-multidimensional-array-in-c