【发布时间】: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)与“适当的大小”完全无关 - 当您分配微小的数组并在它们的末尾写下距离时,几乎任何事情都可能发生。