1

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?

cadaniluk
  • 15,027
  • 2
  • 39
  • 67
Cesare
  • 9,139
  • 16
  • 78
  • 130
  • 1
    [The first index of an array is `0`.](http://stackoverflow.com/questions/7320686/why-does-the-indexing-start-with-zero-in-c) – cadaniluk Dec 06 '15 at 18:34
  • 1
    Do not correct your question. How else are others supposed to know what your mistake was? – cadaniluk Dec 06 '15 at 18:37

2 Answers2

5

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.

Neil
  • 641
  • 1
  • 7
  • 21
Am_I_Helpful
  • 18,735
  • 7
  • 49
  • 73
  • There is another flaw in the code. OP passes an unitialised array to his function which (he says) prints it. – Weather Vane Dec 06 '15 at 19:06
  • @WeatherVane - Actually, I believe OP's intentions where just to know why code is not working, because at the starting of the question, OP said that their array contains given elements... But, thanks, I'll make a necessary edit. – Am_I_Helpful Dec 06 '15 at 19:16
  • @Am_I_Helpful I only went pedantic because OP asked *"So this is my only code's flaw?"* which I took to mean *"So this is my code's only flaw?"*. I take your point about it actually being initialised, but the code itself skipped that part. – Weather Vane Dec 06 '15 at 19:28
2

Pass matrix[1] instead of matrix[2], because indices always start from zero.

Am_I_Helpful
  • 18,735
  • 7
  • 49
  • 73
shaikh
  • 129
  • 1
  • 11