2

In C if I have:

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? writing this won't help grades[][0]

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • 4
    It's not possible to pass a column. Pass the whole array and the column index as separate parameters. – Barmar Jul 14 '20 at 13:45
  • @Barmar Better, make a struct that stores those together. – Alexander Jul 14 '20 at 13:47
  • The rows are their own "entities", but the columns aren't. They're just slivers of each of the rows. If you want to make an array representing the column, you'll need to walk the array of rows and copy the elements into a new row array, yourself. See: http://math.hws.edu/javanotes/c7/s5.html – Alexander Jul 14 '20 at 13:48

3 Answers3

4

You can't pass columns in 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.

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

3

If it helps to visualize, a 2-dimensional array is an array of arrays, it's not formulated as a matrix. Thereby, we can pass a sub-array (i.e., a row), but there's no direct way of passing a 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.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

Matrixes do not exist in C (check by reading the C11 standard n1570). Only arrays, and in your example, it is an array of arrays of int. 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.

In some cases, arbitrary precision arithmetic (with gmplib) could be needed.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547