我从包含质量和点的(x,y,z)位置的文件中获得数据。我现在想要获取给定的数据并使用多维数组将其输出到文件中。但是,我不知道如何获取扫描数据并在阵列中使用它。
我的数据存储如下:
for(i = 0; i < n; i++) //scan in file data
{
fscanf(fpin, "%d %d %d %d", &array_x[i], &array_y[i], &array_z[i], &array_mass[i]);
}
我尝试将我的数组设置为[][4]
,因为行数取决于给定的数据点数(并且说明是编写一个适用于任意数量数据点的数组,而不仅仅是给出了什么),将有4列(分别为x,y,z和质量)。
然后我尝试将其设置为:
for(i = 0; i < n; i++)
{
array_out[i][4] = { {array_x[i]}, {array_y[i]}, {array_z[i]}, {array_mass[i]} };
}
将其打印为:
for(i = 0; i < n; i++)
for(j = 0; j < n; j++)
fprintf(fpout, "%d %d %d %d", array[i][j]);
但这不起作用。
答案 0 :(得分:0)
您知道需要阅读多少元素吗?如果这样做,那么您可以分配一个数组来保存它们。如果不这样做,则需要动态存储。
你的质量和点(x,y,z)有哪些类型?请提供样品。
你的printf格式说明符可能有问题(你真的是指%d,因为它不是双倍的)? (见:C printf using %d and %f)
声明一个结构来包含你的点/质量,以及处理pointmass的基本函数(方法),
声明存储,
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(es)扫描到声明的pointmass数组中,
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));
}
请记住释放所有这些pointmass元素,
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元素。