typedef struct Spheres{
    int PositionX;
    int PositionY;
    int Color;
    int Mass;
    int Radius;
    int SpeedX;
    int SpeedY;
}Sphere;

char readFile(FILE *file,Sphere **totalSphere){
    int positionX,positionY,color,mass,radius,speedX,speedY,amountOfSpheres,i;
    fscanf(file,"%d",&amountOfSpheres);
    *totalSphere=malloc(amountOfSpheres*sizeof(Sphere));
    for (i=0;i<amountOfSpheres;i++){
        fscanf(file,"%d%d%d%d%d%d%d",&positionX,&positionY,&color,&mass,&radius,&speedX,&speedY);
        totalSphere[i]->PositionX=positionX;
        totalSphere[i]->PositionY=positionY;
        totalSphere[i]->Color=color;
        totalSphere[i]->Mass=mass;
        totalSphere[i]->Radius=radius;
        totalSphere[i]->SpeedX=speedX;
        totalSphere[i]->SpeedY=speedY;
    }
    printf("%d %d %d %d %d %d %d\n",totalSphere[0]->PositionX,totalSphere[0]->PositionY,totalSphere[0]->Color,totalSphere[0]->Mass,totalSphere[0]->Radius,totalSphere[0]->SpeedX,totalSphere[0]->SpeedY);
    printf("%d %d %d %d %d %d %d\n",totalSphere[1]->PositionX,totalSphere[1]->PositionY,totalSphere[1]->Color,totalSphere[1]->Mass,totalSphere[1]->Radius,totalSphere[1]->SpeedX,totalSphere[1]->SpeedY);
}


int main()
{
    FILE *file;
    Sphere *totalSphere;
    totalSphere=NULL;
    if ((file=fopen("input.txt","r"))!=NULL){
        if (readFile(file,&totalSphere)){
            printf("%d %d %d %d %d %d %d\n",totalSphere[0].PositionX,totalSphere[0].PositionY,totalSphere[0].Color,totalSphere[0].Mass,totalSphere[0].Radius,totalSphere[0].SpeedX,totalSphere[0].SpeedY);
            printf("%d %d %d %d %d %d %d\n",totalSphere[1].PositionX,totalSphere[1].PositionY,totalSphere[1].Color,totalSphere[1].Mass,totalSphere[1].Radius,totalSphere[1].SpeedX,totalSphere[1].SpeedY);
            fclose(file);
    return 0;
}


这是我的代码,
this是我正在读取的文本文件

问题在于,当函数readFile()结束时,如您看到的here一样,totalSphere [1]中的值会丢失,但是totalSphere [0]中的值还可以。为什么会这样呢?

最佳答案

显然,您在间接级别上迷路了。您在Sphere内部分配的readFile对象数组应该以(*totalSphere)[i]的形式访问。例如

for (i = 0; i < amountOfSpheres; i++) {
  fscanf(file, "%d%d%d%d%d%d%d", &positionX, &positionY, &color, &mass, &radius, &speedX, &speedY);
  (*totalSphere)[i].PositionX = positionX;
  (*totalSphere)[i].PositionY = positionY;
  ...


您的原始版本不正确。

(*totalSphere)[i]语法在readFile内适用,因为totalSphereSphere **内。在main中,您将以“常规”方式访问收到的数组-为totalSphere[i]

09-05 14:13