Savvas Savvas - 10 months ago 97
C Question

Pointer to struct doesn't work properly?

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 is my code and
this is the text file i'm reading from

The problem is that when the function readFile() ends, the values from totalSphere[1] are lost as you can see here but the values from totalSphere[0] are ok. Why is this happening?

AnT AnT
Answer Source

You got lost in levels of indirection, apparently. The array of Sphere objects that you allocated inside readFile is supposed to be accessed as (*totalSphere)[i]. E.g

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;
  ...

Your original version is incorrect.

The (*totalSphere)[i] syntax applies inside readFile, since totalSphere is Sphere ** there. In main you will access the received array the "regular" way - as totalSphere[i].

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download