0

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;
3
  • You appear to be assigning the same variable to rooms[numOfRooms].Name so why would you expect them to have different values? Commented Apr 24, 2018 at 15:04
  • regarding: rooms=(struct room*)malloc(sizeof(*rooms)); 1) the returned type from any of the heap allocation functions: malloc calloc realloc, si void* 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 to malloc can be eliminated. Commented Apr 24, 2018 at 21:56
  • regarding: rooms=(struct room*)realloc(rooms,sizeof(*rooms)*(numOfRooms+1)); 1) don't cast the returned value (see my prior comment) Commented Apr 24, 2018 at 21:58

2 Answers 2

2

When you do this:

rooms[numOfRooms].Name=name;

You're making Name point to the same thing that name points to. It is not copying the value. This means that all of your room instances have their Name member pointing to the same place.

You should use strdup to create a new dynamically allocated string from the one you use to read the user input:

rooms[numOfRooms].Name=strdup(name);

Be sure to call free on this field when you're done with it.

Sign up to request clarification or add additional context in comments.

Comments

0

variable name is not declared.

This is very likely the wrong way to assign a variable.
(but since you didn't show the declaration of name, it is hard to be sure)

rooms[numOfRooms].Name=name;  // Use Strcpy, strdup, or similar.

2 Comments

char string[20]; char temp; char * name=string;
name was delared

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.