0

I have the following struct:

typedef struct{
    char* name;
    int score;
}Student;

typedef struct{
    char* name;
    int score;
}TeachingAssistant;

I have already strdup'd a string into the name variable in the Student struct.

I wanted to know how can I move that strdup'd name pointer variable to the TeachingAssistant struct so that I don't have to strdup again.

dbush
  • 205,898
  • 23
  • 218
  • 273
John
  • 105
  • 1
  • 8

2 Answers2

1

You probably still want to use strdup when populating name in a TeachingAssistant struct. If you don't, and simply copy the pointer, then if you free the pointer in one struct the other one becomes invalid. You'd have to implement schemes to keep track of pointer references otherwise.

Better to just strdup the string where you need it, and free it for each copy when you don't need it anymore.

dbush
  • 205,898
  • 23
  • 218
  • 273
0
typedef struct{
  Student *XYZ;
  //char* name;
  //int score;
}TeachingAssistant;

Instead of definition you have right now , you can declare a pointer to struct Student as a member of struct TeachingAssistant , so that you can access name using it and no need to create duplicate .

ameyCU
  • 16,489
  • 2
  • 26
  • 41