I am trying to change a variable in a struct object. But every time I change it, other objects will change as well.
Here is my struct
struct room{
char * S;
char * N;
char * W;
char * E;
char South;
char North;
char West;
char East;
char * Name;
};
and here is block I ran in main method
int numOfRooms=0;
struct room * rooms;
rooms=(struct room*)malloc(sizeof(*rooms));
do{
rooms=(struct room*)realloc(rooms,sizeof(*rooms)*(numOfRooms+1));
fscanf(fp,"%s%c",name,&temp);
printf("%s ",name);
printf("%d",numOfRooms);
rooms[numOfRooms].Name=name;
printf("%s ",rooms[0].Name);
numOfRooms++;
}while(temp!='\n');
and the output is: START 0START FOYER 1FOYER ELEVATOR 2ELEVATOR
which should be: START 0START FOYER 1START ELEVATOR 2START
that's my problem. Every time I try to change Name in my struct, the Name for previous ones change as well.
name was declared
char string[20];
char defa[16]="No Path This Way";
char temp;
char * input;
char * name=string;
rooms[numOfRooms].Nameso why would you expect them to have different values?rooms=(struct room*)malloc(sizeof(*rooms));1) the returned type from any of the heap allocation functions:malloccallocrealloc, sivoid*which can be assigned to any pointer. Casting just clutters the code, making it more difficult to understand, debug, etc. 2) if the declaration of rooms is changed to:struct room * rooms = NULL;then the call tomalloccan be eliminated.rooms=(struct room*)realloc(rooms,sizeof(*rooms)*(numOfRooms+1));1) don't cast the returned value (see my prior comment)