假设我有
struct student
{
char* first_name;
};
typedef struct
{
struct student name;
} Person;
char* first_name_of_someone = "John";
为什么我必须 malloc 然后 strcpy 才能将 John 放入 first_name?为什么我不能像这样分配它
Person* person = malloc(sizeof(Person));
struct student s;
s.first_name = "John";
person->name = s;
最佳答案
如果您事先知道要复制什么值,那么您就不需要 malloc
s.first_name = "John";
如果您开始知道在运行时要复制什么值怎么办?
在这种情况下,您需要 malloc
和 strcpy
。
fgets(tempbuf, sizeof tempbuf, stdin);
s.first_name = malloc(somelength);
strcpy(s.first_name, tempbuf);
或
s.first_name = tempbuf;
在后一种情况下,first_name
将始终指向存储在 tempbuf
中的最新值。
关于c - malloc 然后 strcpy 与仅将其设置为等于字符串之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55931600/