首页 > 解决方案 > malloc 然后 strcpy 与将其设置为等于字符串之间的区别

问题描述

假设我有

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;

标签: c

解决方案


如果您事先知道要复制什么值,那么您就不需要malloc

s.first_name = "John";

如果您要知道在运行时要复制什么值怎么办?在这种情况下,您需要mallocand strcpy

fgets(tempbuf, sizeof tempbuf, stdin);

s.first_name = malloc(somelength);
strcpy(s.first_name, tempbuf);

或者

s.first_name = tempbuf; 

在后一种情况下first_name,将始终指向存储在tempbuf.


推荐阅读