你知道你需要阅读多少元素吗?如果你这样做,那么你可以分配一个数组来保存它们。如果不这样做,则需要动态存储。
你的质量和点(x,y,z)的类型是什么?请提供样品。
您的 printf 格式说明符可能有问题(您真的是指 %d,因为它不是双重的)? (见:C printf using %d and %f)
声明一个结构来包含您的点/质量,以及处理点质量的基本函数(方法),
声明存储,
typedef struct pointmass_struct {
double mass;
double x,y,z;
} pointmass_t ;
声明函数/方法,
pointmass_t*
pm_new( double mass, double x, double y, double z ) {
pointmass_t* this;
if( ! (this=malloc(sizeof(pointmass_t)) ) return(NULL);
this->mass = mass;
this->x = x;
this->y = y;
this->z = z;
return(this);
}
void
pointmass_del( pointmass_t* pm ) {
if(pm) free(pm);
return;
}
pointmass_t*
pointmass_fromstr( char* line ) {
double x, y, z, m;
sscanf(line, "%f %f %f %f", &x, &y, &z, &m );
pointmass_t* this = pointmass_new( x, y, z, m );
return( this );
}
pointmass_t*
pointmass_fscanf( FILE* fp ) {
double x, y, z, m;
fscanf(fp, "%f %f %f %f", &x, &y, &z, &m );
pointmass_t* this = pointmass_new( x, y, z, m );
return( this );
}
char*
pointmass_tostr( pointmass_t* this, char* buff ) {
if( !buff ) return(buff);
sprintf(buff, "%f %f %f %f", this->x, this->y, this->z, this->mass );
return(buff);
}
int
pointmass_print( pointmass_t* this )
{
char pmbuff[100];
return( printf("%s\n",pointmass_tostr(this,pmbuff) ) );
}
扫描一个点,
pointmass_t* pm = pointmass_fscanf(fpin);
将许多点质量扫描到声明的点质量数组中,
pointmass_t* pm_array[100]; //pick a suitable size
for(i = 0; i < n; i++) //scan point/mass elements from file
{
pm_array[i] = pointmass_fscanf(fpin);
}
char pmbuff[100];
for(i = 0; i < n; i++) //print them
{
printf("[%d] %s\n",pointmass_str(pm_array[i],pmbuff));
}
跟踪数组有多大,并动态增加大小,
pointmass_t** pm_dynarray;
int pmsize = 0;
pm_dynarray = malloc( (pmsize=500) * sizeof(pointmass_t*));
for(i = 0; i < n; i++) //scan from file
{
if( i+1 > pmsize ) {
pm_dynarray = realloc( (pmsize+=100) * sizeof(pointmass_t*));
}
pm_dynarray[i] = pointmass_fscanf(fpin);
}
for(i = 0; i<pmsize; i++ )
{
printf("[%d] %s\n",i,pointmass_str(pm_dynarray[i],pmbuff));
}
记得释放所有这些点状元素,
for(i = 0; i<pmsize; i++ )
{
if(pm_dynarray[i]) pointmass_del(pm_dynarray[i]);
pm_dynarray[i] = NULL;
}
//now safe to free the array
free(pm_dynarray); pm_dynarray=NULL; pmsize=0;
更好的是,使用链表来存储 pointmass 元素。