c - fscanf() 和 realloc() - 将文件读取到矩阵

标签 c file malloc scanf realloc

我在动态读取文件到二维数组时遇到问题。我已经阅读了很长时间,但我仍然不知道如何强制我的代码工作。

我的代码:http://codepaste.net/3hcbtn

#include <stdio.h>
#include <stdlib.h>
int main(){
//This program reads a file consisting of 5 columns of numbers.
//We assume that we don't know the number of rows of that file. 
double **x,**t;    
int i,j,COL=5;

x=malloc(COL*sizeof(double*));
        for(i=0;i!=COL;i++){x[i]=calloc(1,sizeof(double));}

t=malloc(COL*sizeof(double*));

FILE *f;    
f=fopen("realloc2.dat","r");

j=0;
        for(;;){
                for(i=0;i!=COL-1;i++){
                        fscanf(f,"%lf, ",&x[i][j]);
                        t[i]=realloc(x[i],sizeof(x[i]+1));
                        x[i]=t[i];
                }
                fscanf(f,"%lf\n",&x[COL-1][j]);
                        if(feof(f)!=0){break;}
                t[COL-1]=realloc(x[COL-1],sizeof(x[COL-1]+1));
                x[COL-1]=t[COL-1];

                j++;
        }

for(i=0;i!=COL;i++){
        free(x[i]);
}
free(x);
free(t);
fclose(f);

return 0;
}

输出:

*** Error in `./realloc2_2': realloc(): invalid next size: 0x0000000001d9d040 ***
[...]
Segmentation fault

我有一个包含 COL 列的文件,但我们不知道它有多少行,这就是我尝试使用 realloc() 的原因。我花了很多时间试图修复它...你能帮助我吗?

谢谢。

最佳答案

像这样修复:

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

int main(void){
    double **x;
    int ROW = 5;//Provisional value
    int COL = 5;
    int c, r = 0, rows;

    FILE *fp = fopen("realloc2.dat","r");
    if(fp == NULL){
        perror("file can't open");
        exit(EXIT_FAILURE);
    }

    x = malloc(ROW * sizeof(double*));//malloc(ROW * sizeof(*x));
    for(;;++r){
        if(r == ROW){
            ROW += 5;//fitly size expansion. e.g ROW *= 2
            if((x = realloc(x, ROW * sizeof(*x))) == NULL){
                perror("failed realloc");
                exit(EXIT_FAILURE);
            }
        }
        if((x[r] = malloc(COL * sizeof(double))) == NULL){
            perror("failed malloc");
            exit(EXIT_FAILURE);
        }
        for(c = 0; c < COL; ++c){
            if(1 != fscanf(fp, "%lf", &x[r][c]))
                goto readend;
        }
    }
readend:
    rows = r;
    if(c != 0){
        puts("data are insufficient.");
    } else {
        //test print
        for(r = 0; r < rows; ++r){
            for(c = 0; c < COL; ++c){
                if(c)
                    putchar(' ');
                printf("%5.2f", x[r][c]);
            }
            puts("");
        }
    }
    fclose(fp);
    //deallocate
    for(r = 0; r <= rows; ++r){
        free(x[r]);
    }
    free(x);

    return 0;
}

关于c - fscanf() 和 realloc() - 将文件读取到矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39030056/

相关文章:

c++ - 优化数学表达式

file - Moodle 中的日志文件位于哪里?

c - UART1_Read_Text() 问题

c - 从 ASM 返回一个 int*

c - 为什么这个函数以大写形式显示?

c - 'void*' 到 'struct*' 的无效转换

c - malloc 内存中的数据损坏

linux - 检索进程曾经在 linux 中打开的所有文件描述符(文件)的列表

file - 使用 AppleScript 删除文件以回收站或永久

c - 如何在 C 中声明足够大的缓冲区?