Cesare Cesare - 2 months ago 10
C Question

How do I pass the elements of a row of a matrix to a function?

Say I have a multi-dimensional matrix in C,

matrix[2][3]
, whose elements look like this:

1 3 5
2 3 4


I would like to pass the second row of the matrix (as an array) to a function. I do it this way:

void myFunction(int array[]) {
}

int main() {
int matrix[2][3];
myFunction(matrix[2]);
}


Though, when I print the values of the
array[]
inside
myFunction
the elements look all set to zero:

0 0 0


How do I pass the elements of row of a matrix to a function properly?

Answer

matrix[2] is not a pre-defined location in your code. You need to pass matrix[1] to access the 2nd row.

By the way, the array you seem to pass is uninitialized. Please initialize it before passing to the function.

Like, in your case, the code should be :-

void myFunction(int array[]) {
...// and so on
}

int main() {
int matrix[2][3] = {{1,3,5},{2,3,4}};
myFunction(matrix[1]);
...// and so on
return 0;
}

Note: array indices in C always start from 0.