0
int main(){
int word, r=3, i, j;
FILE *fp1 = fopen("key.txt","r");

int **arr  = (int **)malloc(sizeof(int *) * r);

for(i = 0;i<r;i++)
    arr[i] = (int *)malloc(sizeof(int)*r);

int a = 0, b = 0;
while (!feof(fp1)) {
    fscanf(fp1,"%d",&word);
    if (b == r){
        a++;
        b=0;
        continue;
    }

    arr[a][b++] = word;

}


for (i = 0; i <  r; i++)
    for (j = 0; j < r; j++)
        printf("%d \n", arr[i][j]);

fclose(fp1); 
}

And this is my key.txt.

0 -1 0
-1 2 -1
0 -1 0

I want to store key.txt in a dynamic 2d array but it did not work. All the time a part of it is missing. Which part is wrong?

dreamer
  • 47
  • 4
  • 1
    This is a good opportunity starting to learn to use a [debugger](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems). Also, please format your code properly! One can't read this. – hellow Oct 29 '18 at 10:58
  • 1
    The check for the row-wrap should come after the assignment, immediately after you increment `b`. Conceptually, moving to the right and starting a new row if necessary belong together; it's one "move". You should also `break` the loop when the matrix is full, i.e. when `a == r`. – M Oehm Oct 29 '18 at 11:07
  • @Tretorn it depends which `malloc` you're talking about. – Jabberwocky Oct 29 '18 at 11:17
  • 1
    The continue statement leads to skipping values, which is probably undesirable (comment it out, and see what happens). – Danny Ruijters Oct 29 '18 at 11:21
  • also, you are not free the allocated memory – Danny Ruijters Oct 29 '18 at 11:22
  • @Jabberwocky I was talking about the first one. But i've also read he needed the row length to be dynamic, so, indeed he needs to use that ** and `int* ` – Tretorn Oct 29 '18 at 11:25
  • @Tretorn then you should delete your comment. – Jabberwocky Oct 29 '18 at 11:27
  • If you use real 2D arrays instead, a single fread/fwrite would be enough. – Lundin Oct 29 '18 at 12:59

1 Answers1

3
  1. You should use fscanf in while, not feof
  2. You should delete continue.

The follow code could work:

#include <stdio.h>
#include <stdlib.h>

int main(){
    int word, r=3, i, j;
    FILE *fp1 = fopen("key.txt","r");

    int **arr  = (int **)malloc(sizeof(int *) * r);

    for(i = 0;i<r;i++)
        arr[i] = (int *)malloc(sizeof(int)*r);

    int a = 0, b = 0;
    while (fscanf(fp1,"%d",&word) == 1) {
        if (b == r) {
            a++;
            b=0;
        }
        arr[a][b++] = word;
    }

    for (i = 0; i < r; i++) {
        for (j = 0; j < r; j++)
            printf("%d ", arr[i][j]);
        printf("\n");
    }

    fclose(fp1);
    return 0;
}
Yunbin Liu
  • 1,484
  • 2
  • 11
  • 20