0

基本上,我正在从文本文件中读取一堆值,它们的布局如下:

4 1 1 2 3 4

但是下面的代码块不想读取前两个 int 类型值之后的 double 类型值:

int matrix_read(struct matrep *mat, const char *filename)
{
    FILE *fptr;
    unsigned m, n;
    double *ptr = NULL;
    int i, j;
    double x;
    if ((fptr = fopen(filename, "r")) == NULL)
    {
        fprintf(stderr, "Cannot Open File %s\n", filename);
        return -1;
    }
    if(fscanf(fptr, "%u", &m) != 1)
    {
        fprintf(stderr, "Failed to read number of rows\n");
        return -1;
    }
    if(fscanf(fptr, "%u", &n) != 1)
    {
         fprintf(stderr, "Failed to read number of columns\n");
        return -1;
    }

    mat->matrix = (double *)malloc(sizeof(double) * m * n);
    if (mat->matrix == 0)
    {
        fprintf(stderr, "Failed to allocate %d*%d matrix\n", m, n);
        return -1;
    }
    ptr = mat->matrix;

    for (i = 0; i < m; i++)
    {
        for (j = 0; j < n; j++)
        {
            double x;
            if (fscanf(fptr, "%f", &x) != 1)
            {
                fprintf(stderr, "Failed to read element matrix[%d,%d]\n", i, j);
                free(mat->matrix);
                mat->matrix = 0;
                mat->cols = 0;
                mat->rows = 0;
                return -1;
            }
            *ptr++ = x;//Here it reads nothing, it just gives me: -9.2559604281615349e+061
        }
    }
    fclose(fptr);
    mat->cols = m;
    mat->rows = n;

    return 0;  // Success   
}

我究竟做错了什么?

4

1 回答 1

5
fscanf(fptr, "%f", &x)

对于扫描doubles,您需要%lf格式。%f扫描一个float。使用错误的格式会调用未定义的行为,可能发生的情况是扫描的值被转换为 afloat然后存储在指向的前四个字节中double

于 2012-11-12T11:28:37.973 回答