So, I'll preface this by saying I'm fairly new to pointers and dynamic allocation. Currently I am trying to store a file that contains a 3x3 matrix of ints into a 2d array. I've tried debugging my code and what I notice is that it reads my first 2 values, but than begins to generate random garbage into my 2d array. I assume that I am storing my ints incorrectly and there is a flaw in my logic, but as I keep trying to think about it, I can't seem to find where it could be incorrect as they are moving from [0][0], [0][1], etc.
Here is my code for reference. Thanks, I'd appreciate just some guidance on how I can troubleshoot this problem for this specific case and future issues.
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE* fpM1;
fpM1 = fopen("m1.txt", "r");
int i, j, row1 = 2, col1 = 2;
int* ptrM1 = (int* )malloc(9 * sizeof(int));
if (fpM1 != NULL) {
for (i = 0; i < row1; i++) {
for (j = 0; j < col1; j++) {
fscanf(fpM1, "%d", ((ptrM1 + i) + j));
}
}
for (i = 0; i < row1; i++)
for (j = 0; j < col1; j++) {
{
printf(" %d", *((ptrM1 + i) + j));
}
}
}
free(ptrM1);
fclose(fpM1);
return 0;
}
Your for loops end too fast. You should use <= instead of <. After that, everything seems to work perfectly.
Maybe you should consider adding new line in outer for loop during printing array. It will help with clarity:
for (i = 0; i < row1; i++) {
for (j = 0; j < col1; j++) {
printf(" %d", *(ptrM1 + i));
}
printf("\n");
}
Also you don't need those double brackets before first printf statement. In C you can put many scopes without context, but you shouldn't do that without reason.
EDIT: It actually doesn't work. Reading from file should be done this way:
fscanf(fpM1, "%d", ptrM1 + (i * (col1 + 1) + j));
and printing:
printf(" %d", ptrM1[i * (col1 + 1) + j]);