简体   繁体   English

在 C99 中获取数组列?

[英]getting column of array in C99?

In C if I have:在 C 如果我有:

int grades[100][200];

and want to pass the first row, then I write: grades[0] , but what if I want to pass first column?并想通过第一行,然后我写: grades[0] ,但是如果我想通过第一列怎么办? writing this won't help grades[][0]写这个不会帮助grades[][0]

You can't pass columns in C.您不能传递 C 中的列。 You pass pointers to the beginning of some continuous data.您将指针传递给一些连续数据的开头。

Rows in C are written continuously in memory, so you pass the pointer to the first element of some row (you do it implicitly by using its name: matrix[row] ; an explicit version would be &matrix[row][0] ), and you can use the row by iterating over the continuous memory. C 中的行在 memory 中连续写入,因此您将指针传递给某行的第一个元素(您可以使用其名称隐式执行此操作: matrix[row] ;显式版本将是&matrix[row][0] ),您可以通过迭代连续的 memory 来使用该行。

To use columns, you need to pass the whole array (a pointer to the first element in the 2D array, actually), and pass also the length of the rows, and then the function has to jump that length to jump from an element of the same column to the next one.要使用列,您需要传递整个数组(实际上是指向二维数组中第一个元素的指针),并传递行的长度,然后 function 必须跳过该长度才能从元素跳转同一列到下一个。 This is one of many possible solutions, you could develop any other solution, for example copying the column in a temporary array as some comment pointed out;这是许多可能的解决方案之一,您可以开发任何其他解决方案,例如将列复制到临时数组中,正如一些评论指出的那样; but this one is commonly used in cblas functions for example.但是这个通常用于例如cblas函数。

If it helps to visualize , a 2-dimensional array is an array of arrays, it's not formulated as a matrix .如果它有助于可视化,二维数组是 arrays 的数组,它不是矩阵 Thereby, we can pass a sub-array (ie, a row), but there's no direct way of passing a column .因此,我们可以传递一个子数组(即一行),但没有直接的方法来传递一个column

One way to achieve this is to loop over the outer array, pick the element at the fixed location (mimicking the "column"), and use the values to create a separate array, or pass to function that needs to process the data.实现此目的的一种方法是遍历外部数组,在固定位置选择元素(模仿“列”),并使用这些值创建一个单独的数组,或传递给需要处理数据的 function。

Matrixes do not exist in C (check by reading the C11 standard n1570 ). C 中不存在矩阵(通过阅读 C11 标准n1570 进行检查)。 Only arrays, and in your example, it is an array of arrays of int .只有 arrays,在您的示例中,它是int的 arrays 的数组。 So columns don't exist neither.所以列也不存在。

A good approach is to view a matrix like some abstract data type (using flexible array members ....) See this answer for details.一个好的方法是查看一些抽象数据类型的矩阵(使用灵活的数组成员......)有关详细信息,请参阅此答案

Consider also using (and perhaps looking inside its source code) the GNU scientific library GSL , and other libraries like OpenCV , see the list here .还可以考虑使用(并且可能查看其源代码)GNU 科学库GSL和其他库,如OpenCV ,请参阅此处的列表。

In some cases, arbitrary precision arithmetic (with gmplib ) could be needed.某些情况下,可能需要任意精度算术(使用gmplib )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM