为什么不能动态分配此结构字符串的内存? [英] Why can't I dynamically allocate memory of this string of a struct?

查看:48
本文介绍了为什么不能动态分配此结构字符串的内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有一个结构:

typedef struct person {
    int id;
    char *name;
} Person;

我为什么不能执行以下操作:

Why can't I do the following:

void function(const char *new_name) {
    Person *human;

    human->name = malloc(strlen(new_name) + 1);
}


推荐答案

您需要为以下内容分配空间 human 首先:

You need to allocate space for human first:

Person *human = malloc(sizeof *human);

human->name = malloc(strlen(new_name) + 1);
strcpy(human->name, new_name);

这篇关于为什么不能动态分配此结构字符串的内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆