多维数组-fscanf

时间:2018-10-29 10:52:20

标签: c multidimensional-array dynamic-memory-allocation

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); 
}

这是我的key.txt。

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

我想将key.txt存储在动态2D数组中,但是它不起作用。一直都有一部分丢失。哪一部分错了?

1 个答案:

答案 0 :(得分:3)

  1. 您应该在fscanf中使用while,而不是feof
  2. 您应该删除continue

关注code可能会起作用:

#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;
}