Processing the columns of a multidimensional array in C

对着背影说爱祢 提交于 2020-01-23 12:05:53

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!