从文件中读取二维数组并打印它

时间:2017-10-15 22:29:44

标签: c arrays linux gcc

我的代码有些问题。一切都好; gcc没有显示错误或警告; valgrind说没有内存泄漏,但我的阵列没有打印,我不知道为什么。 fscanf()无法正常工作或我打印错误吗?

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

int arrsize (FILE *file)
{
    if (file == NULL) {
        printf("Error: file pointer is null.");
        return 0;
    }
    int sizer;
    fscanf(file, "%d", &size);
    return size;
}


int main()
{
    int i = 0, j = 0, k = 0,a=0;

    FILE *fp;
    if ((fp = fopen("matrix.txt", "r")) == NULL)
    {
        printf("Error: file pointer is null.\n");
        return 1;
    }
    int size = arrsize(fp);

    printf("Array size is %d x %d \n", size, size);

    double **array = (double **)malloc(size * sizeof(double *));
    for (i; i < size; i++)
       array[i] = (double *)malloc(size * sizeof(double));

    for (i; i < size; i++)
    {
        for (j = 0; j < size; j++)
        {
            fscanf(fp, " %lf", &array[i][j]); 
            printf(" %lf ",array[i][j]);
        }
    }

    for (k ; k < size; k++) {
        free(array[k]);        
    }
    free(array);

    fclose(fp);
    return 0;
}

1 个答案:

答案 0 :(得分:0)

检查fscanfmalloc的返回以确保成功 将fflush ( stdout);添加到打印循环,因为格式字符串没有换行符。

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

int arrsize (FILE *file)
{
    if (file == NULL) {
        printf("Error: file pointer is null.");
        return 0;
    }
    int size;
    if ( 1 == fscanf(file, "%d", &size)) {
        return size;
    }
    return -1;
}


int main()
{
    int i = 0, j = 0, k = 0;

    FILE *fp;
    if ((fp = fopen("matrix.txt", "r")) == NULL)
    {
        printf("Error: file pointer is null.\n");
        return 1;
    }
    int size = arrsize(fp);
    if ( -1 == size) {
        fprintf( stderr, "Error: problem parsing array size.\n");
        return 1;
    }

    printf("Array size is %d x %d \n", size, size);

    double **array = NULL;
    if ( NULL != ( array = malloc(size * sizeof(double *)))) {
        for (i = 0; i < size; i++) {
            if ( NULL == ( array[i] = malloc(size * sizeof(double)))) {
                fprintf ( stderr, "problem allocation array[]\n");
                while ( i) {
                    i--;
                    free ( array[i]);
                }
                free ( array);
                return 1;
            }
        }
    }
    else {
        fprintf ( stderr, "problem allocation array\n");
        return 1;
    }

    for (i = 0; i < size; i++)
    {
        for (j = 0; j < size; j++)
        {
            if ( 1 == fscanf(fp, "%lf", &array[i][j])) {
                printf(" %lf ",array[i][j]);
            }
            else {
                fprintf ( stderr, "problem parsing double\n");
                break;
            }
        }
        fflush ( stdout);
    }

    for (k = 0; k < size; k++) {
        free(array[k]);
    }
    free(array);

    fclose(fp);
    return 0;
}