【问题标题】:Why can't I dynamically allocate memory of this string of a struct?为什么我不能动态分配这个结构字符串的内存?
【发布时间】:2014-12-06 06:40:24
【问题描述】:

比如说,我有一个结构体:

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

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

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

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

【问题讨论】:

  • 你有一个指向人类的指针,但你还没有为人类本身分配新的空间。
  • @user2899162:听起来更像是失败的国内政策,而不是编程问题!

标签: c struct dynamic-memory-allocation strcpy


【解决方案1】:

您必须为结构Person 分配内存。指针应该指向为结构分配的内存。只有这样,您才能操作结构数据字段。

结构Person 包含id, 和指向名称的char 指针name。您通常希望为名称分配内存并将数据复制到其中。 在程序结束时记得释放namePerson 的内存。 发布顺序很重要。

提供了一个小示例程序来说明这个概念:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

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


Person * create_human(const char *new_name, int id) 
{
    Person *human = malloc(sizeof(Person));       // memory for the  human

    human->name = malloc(strlen(new_name) + 1);   // memory for the string
    strcpy(human->name, new_name);                // copy the name

    human->id = id;                               // assign the id 

    return human; 
}

int main()
{
    Person *human = create_human("John Smith", 666);

    printf("Human= %s, with id= %d.\n", human->name, human->id);

    // Do not forget to free his name and human 
    free(human->name);
    free(human);

    return 0;
}

输出:

Human= John Smith, with id= 666.

【讨论】:

    【解决方案2】:

    你需要先为human分配空间:

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

    【讨论】:

    • 你不是要 malloc 结构的大小而不仅仅是一个指针吗? @barmar -sizeof(*huamn
    猜你喜欢
    • 1970-01-01
    • 2016-04-06
    • 2018-08-05
    • 1970-01-01
    • 2018-06-16
    • 1970-01-01
    • 2012-03-12
    • 1970-01-01
    • 2020-11-28
    相关资源
    最近更新 更多