在C中处理多维数组的列 [英] Processing the columns of a multidimensional array in C

查看:84
本文介绍了在C中处理多维数组的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解如何将二维数组的列设置为0.

I'm trying to understand how to set a column of a two dimensional array to 0.

我遵循K.N.的C编程教科书中的此代码段.国王.

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.

推荐答案

这与如何将数组转换为访问时的指针有关,请参见:

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).

在您的情况下,您有一个int a[NUM_ROWS][NUM_COLS];的二维数组.实际上是int[NUM_COLS]的数组的数组. (一维数组的数组).

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).

访问a时,a会转换为指向第一个1D数组的指针,并且类型为int (*)[NUM_COLS](指向NUM_COLS整数数组的指针).

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).

您将p声明为指向NUM_COLS整数数组的指针,因此p在类型上与a兼容.您可以简单地初始化:

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;

(而不是p = &a[0];)

for循环中,您从p = a;(指向第一个1D数组的指针)循环,并在p小于&a[NUM_ROWS](最后一个1D数组之后的地址1)时循环,递增p每次迭代(由于p是指向int[NUM_COLS]的指针,因此每次增加pp都指向下一行)

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)

当取消引用p时,会有一个int[NUM_COLS]的数组,因此当您寻址(*p)[i] = 0;时,会将该行的第i th 元素设置为0.

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.

这篇关于在C中处理多维数组的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆