I have the following struct:
typedef struct{
char* name;
int score;
}Student;
typedef struct{
char* name;
int score;
}TeachingAssistant;
I have already strdup
'da 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.
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.
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 .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.