Reputation: 831
I cannot figure out why the output of my program is so strange. I just wanted to print matrix with pointers, but what I get is:
1 7 3 8 9
10 8 9 3 4
1 7 3 8 9
7 3 8 9 10
What am I doing wrong here?
#include<stdio.h>
#define NK 5
#define NW 2
int sum(int *w);
int main(void) {
srand(time(NULL));
int T[NW][NK];
int i, j;
for (i = 0; i<NW; i++) {
for (j = 0; j<NK; j++) {
T[i][j] = rand() % 10 + 1;
printf("%d ", T[i][j]);
}
printf("\n");
}
int *wsk = T;
printf("\n");
sum(wsk);
return 0;
}
int sum(int *w) {
int i, j;
int suma = 0;
printf("\n");
for (i = 0; i<NW; i++) {
for (j = 0; j<NK; j++) {
printf("%d ", *((w + i)+j));
}
printf("\n");
}
}
Upvotes: 1
Views: 1956
Reputation: 144770
If the geometry is fixed, you can just declare the argument with the proper type:
int sum(int w[NW][NK]) {
printf("\n");
for (int i = 0; i < NW; i++) {
for (int j = 0; j < NK; j++) {
printf("%d ", w[i][j]);
}
printf("\n");
}
}
If you insist on passing a pointer to a linearized version:
int sum(int *w) {
printf("\n");
for (int i = 0; i < NW; i++) {
for (int j = 0; j < NK; j++) {
printf("%d ", w[i * NK + j]);
}
printf("\n");
}
}
Upvotes: 2