c/c++语言开发共享为什么我不能动态分配这个结构字符串的内存?

比方说,我有一个结构:

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

为什么我不能做以下事情:

 void function(const char *new_name) { Person *human; human->name = malloc(strlen(new_name) + 1); } 

    你需要先为human分配空间:

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

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

    结构Person拥有id,并且char指针name为name。 您通常希望为名称分配内存并将数据复制到其中。 在程序结束时记得为namePerson释放内存。 下达订单很重要。

    提供了用于说明概念的小样本程序:

     #include  #include  #include  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. 

      以上就是c/c++开发分享为什么我不能动态分配这个结构字符串的内存?相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/519222.html

      (0)
      上一篇 2020年12月5日
      下一篇 2020年12月5日

      精彩推荐