Error in 2d array index.

Good evening!

In the code bellow, why i'm getting that output instead of 5, 2, 3?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <stdio.h>

void showStock(int a, int p, int stock[][p]);

int main( ) {
	int a = 3;
	int stock[][3] = {{9, 5, 6}, 
					  {8, 2, 1},
					  {7, 3, 4}};

	showStock(a, 2, stock);

	return 0;
}

void showStock(int a, int p, int stock[][p]) {
	int i;
	p--;//To adjust with array index.

	for(i=0; i < a; i++)
		printf("(%d, %d) -> %d\n", i, p,  stock[i][p]);

}


Output:
(0, 1) -> 5
(1, 1) -> 8
(2, 1) -> 1


I want to get:
(0, 1) -> 5
(1, 1) -> 2
(2, 1) -> 3
I changed void showStock(int a, int p, int stock[][p]) to void showStock(int a, int p, int stock[][3]) and it worked.
Thank!
But, look, i changed a little bit this code to post my problem. In my real code i have to read "a", and "p" and after that, declare a 2d array[a][p].
1
2
3
4
5
6
7
8
9
10
11
12
int i, j, a, p;
	scanf("%d", &a);
	scanf("%d", &p);
	int matrix[a][p];
	for(i=0; i < a; i++) {
		for(j=0; j < p; j++) {
			scanf("%d", &matrix[i][j]);
		}
	}
	showStock(a, 2, stock);
	...
	...


Sorry, i tought it would more simple to you to understand my problem.
So, your solution not works because cannot be a fix number(3), i think.
Last edited on
err.. well, you could try it with pointer.
see http://www.cplusplus.com/forum/general/83645/
Topic archived. No new replies allowed.