gpt4 book ai didi

c - 结构体指针不能正常工作?

转载 作者:行者123 更新时间:2023-11-30 14:51:52 25 4
gpt4 key购买 nike

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() 结束时,totalSphere[1] 中的值会丢失,如您所见 here但来自totalSphere[0]的值没问题。为什么会发生这种情况?

最佳答案

显然,您迷失在间接级别中。您在 readFile 中分配的 Sphere 对象数组应该作为 (*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]

关于c - 结构体指针不能正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47948573/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com