Reputation: 3270
Here is my assignment: arrPrintMatrix(int *matrix, int m, int n): prints the content of the matrix[m][n] to the screen in table format.
And here is my code:
#include <stdio.h>
#include <malloc.h>
int main() {
void arrPrintMatrix(int *matrix, int m, int n);
int matrix[2][3] = {{5, 10 , 15}, {0, 2, 4}};
int *ptr;
ptr = &matrix[0][0];
arrPrintMatrix(ptr, 2, 3);
return 0;
}
void arrPrintMatrix(int *matrix, int m, int n) {
int i, j;
for (i = 0; i < m; i++) {
printf("\n");
for (j = 0; j < n; j++) {
printf("%d\t", matrix[i] + j);
}
}
}
But when I run this code, I get 5 6 and 7 as first row, 10 11 and 12 as second row. So something wrong with matrix[i] + j. How should I fix this?
By the way, I'm so confused about arrays of pointers, malloc, pointers to functions, so generally I'm confused about pointers. I would be glad if you suggest some web pages or videos about that.
Upvotes: 2
Views: 4029
Reputation: 206567
Change the line
printf("%d\t", matrix[i] + j);
to
printf("%d\t", matrix[i*n+j]);
Update
Layout of memory of 2D arrays is nicely explained in this article.
Upvotes: 2