I have a question about passing a single column of a matrix to a function. I only need to operate on one column of the whole matrix but I don't seem to have an idea how to do this. I searched the net for an answer, but it seemed that nobody had this question. Thanks for ideas!
-
3a column is generally a non-contiguous memory. There's a notion of "stride". – Jean-François Fabre Mar 04 '18 at 13:51
2 Answers
It costs you nothing to pass the whole array. Then you can manipulate on column data only. If you have different column size in each row you may want to take a look at:
2d dynamic array (in C) with specific row number and different column size in each row.

- 6,108
- 2
- 32
- 40
If you only need to occasionally deal with the data from one column, then just pass the entire matrix, and simply deal with the single column of data when you need to. If you frequently need to deal with a single column of data, you'll have to have a utility function to extract the single column of data, because in C, any array (including an array of arrays) is just a block of memory. C doesn't hold any notion of rows and columns; you have to do that for yourself.
As with most utility functions like this, there are any number of ways to accomplish the goal, and the actual implementation depends more on how you need to use the result than on any particular way of getting the result. One way is like this:
#include <stdlib.h>
#include <stdio.h>
#define NUM_COLS 3
#define ERR_OUT_OF_RANGE 1
#define ERR_NOMEM -1
int get_matrix_column(int (*matrix)[NUM_COLS], int nRows, int iCol, int **result) {
if (iCol < 0 || iCol >= NUM_COLS) return ERR_OUT_OF_RANGE;
*result = malloc(sizeof(int) * nRows);
if (*result == NULL) return ERR_NOMEM;
for (int i = 0; i < nRows; i++) {
(*result)[i] = matrix[i][iCol];
}
return 0;
}
int main(void) {
int matrix[4][3] = { {2, 3, 4}, {7, 8, 9}, {0, 1, 2}, {5, 6, 7} };
int *col = NULL;
int rc = get_matrix_column(matrix, 4, 1, &col);
if (rc)
puts("Error getting column");
else
for (int i = 0; i < 4; ++i) {
printf("%d ", col[i]);
}
free(col);
return 0;
}
This version deals with matrices that are defined with explicit bounds in automatic storage (AKA on the stack). When passed to a function, the pointer-decay for such an array results in a slightly different signature than an array of single elements. The NUM_COLS
macro constant is used because the final dimension in such a declaration has to be constant.
Again, this is just one way out of many. The salient point is that if you want only the values for a single column, you have to go get them yourself, because C has absolutely no idea what you're talking about.

- 2,800
- 9
- 31
- 31