【问题标题】:Printing out extra 2 lines in my code在我的代码中打印出额外的 2 行
【发布时间】:2014-03-09 22:52:21
【问题描述】:

当我在文档中输入值并从同一个循环中打印出来时,我会打印出正确的值。但是,一旦我将这些值放在另一个循环中的数组中,大约一半时我得到了错误的值,其余的都同意。感谢您的帮助!

int main( ){

    int i = 0;
    int n = 0;

    float x, y, x1, y2;

    FILE *fp;

    /*open the file*/

    fp = fopen( "/Users/QuantumEh/Documents/datafiles/table.dat", "r" );

    /*creates array which allocates appropariate size*/


    float *x_axis = (float*) malloc( sizeof( fp ) );
    float *y_axis = (float*) malloc( sizeof( fp ) );

    if ( fp == NULL ){

        printf( "Could not open \n" );
        exit( 0 );
    }

    /*reads in the file*/

    while ( fscanf( fp, "%f %f\n", &x_axis[i], &y_axis[i] ) == 2 ){

        printf( "%.3f %.3f \n", x_axis[i], y_axis[i] );

        i++, n++;

    }



    /* calculates at one-third and then at two-thirds*/

    for ( i = 0; i <= n - 1; i++ ){


        x = x_of_interpolation_onethird( x_axis[i + 1], x_axis[i] ); //finds x of interpolation

        y = lagrange_interpolation( &x_axis[i], &y_axis[i], x ); //plugs in the orignal x and y and the x of interpolation

        x1 = x_of_interpolation_twothird( x_axis[i + 1], x_axis[i] ); //finds the other x of interpolation

        y2 = lagrange_interpolation( &x_axis[i], &y_axis[i], x1 ); //plugs in the orignal x and y and the x of interpolation


        /* prints out all the numbers*/

        //printf("%.3f %.3f \n", x_axis[i], y_axis[i]);
        //printf("%.3f \n", x1);
        //printf("%.3f %.3f\n", x, y);


    }


    return 0;
}

【问题讨论】:

  • 我做 C 文件 IO 已经有一段时间了,但我不认为 sizeof(fp) 会给你足够的分配。
  • sizeof(fp) 与“适当的大小”完全无关 - 当您分配微小的数组并在它们的末尾写下距离时,几乎任何事情都可能发生。

标签: c arrays input output


【解决方案1】:

主要问题是使用下面的代码确定内存分配所需的浮点值数量。 fp 的大小与所需的内存无关。

fp = fopen("/Users/QuantumEh/Documents/datafiles/table.dat", "r");
float *x_axis = (float*) malloc(sizeof(fp));

改为使用其他方法。一种肯定有效但效率有点低的方法是读取磁贴两次。

fp = fopen("/Users/QuantumEh/Documents/datafiles/table.dat", "r");
...
float x,y;
size_t n = 0;
while (fscanf(fp, "%f %f\n", &x, &y) == 2) n++;
float *x_axis = malloc(n * sizeof *x_axis);
float *y_axis = malloc(n * sizeof *y_axis);

rewind(fp);
size_t i = 0;
for (i=0; i<n; i++) {
  if (fscanf(fp, "%f %f\n", &x_axis[i], &y_axis[i])!=2) Handle_UnexpectedError();
} 
fclose(fp);

// Use x_axis, y_axis

// Be sure to free when done
free(x_axis);
free(y_axis);

注意:未经测试的代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-20
    • 2016-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-30
    • 2019-10-01
    • 2018-05-14
    相关资源
    最近更新 更多