c - malloc 然后 strcpy 与仅将其设置为等于字符串之间的区别

标签 c

假设我有

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";

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

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/

相关文章:

c - 自由指针偏移不再有效?

c - 在文本文件中搜索 ID (Turbo c)

c - 避免 double 的精度损失

c - 如何构建Catboost C评估库API?

c - 预处理器不跳过 asm 指令

c - 编译器是否应该对带有 void 指针的指针算法发出警告?

c++ - 仅 header 链接

c - 我应该使用什么图来表示模块中功能之间的交互?

c++ - 音频设备的 ID 名称(waveout c++)

c - fscanf() 只读取一条记录,忽略其余记录