【问题标题】:Char, Malloc, and Struct ArraysChar、Malloc 和结构数组
【发布时间】:2014-03-13 20:55:58
【问题描述】:

我还在学习 C,我有一个关于 char 数组、malloc 和结构的问题。我有以下结构。

函数原型

typedef struct example1{
 char *name[20];
 int ex_id;
 int count;
}example;

在 main.c 中

example *info;
info=(example *)malloc(sizeof(example));
info->name=(char *)malloc(sizeof(char));

printf("Enter ID: ");
scanf("%d", &info[info->count].ex_id);

printf("Enter Name of ID: ");
scanf("%s", info->name[info->count];
getchar();

所以我的问题是我似乎无法在我的结构中使用 malloc char *name[20] 。我想用这个变量做的是动态存储固定强度长度为 20 个字符的名称数量。所以基本上我想要存储的是这样的。

info->name[0]="name1";

info->name[1]="name2";

等等……

【问题讨论】:

    标签: arrays struct char malloc


    【解决方案1】:

    char *name[20]; 这是一个 char* 数组。但是

    info->name=(char *)malloc(sizeof(char));
    

    您只分配 char* 数组元素指向的一个字节。如您所述,为每个索引分配 20 个字节:

    for (i=0;i<20;i++) 
    {
        info->name[i]=(char *)malloc(sizeof(char)*20); 
    }
    

    另外,您将结构指针info 视为一个数组:

    scanf("%d", &info[info->count].ex_id);
    

    您不能这样做,因为:info-&gt;count 未初始化并保存垃圾值。 而且,您通过以下方式为结构的一个对象分配了空间:

    info=(example *)malloc(sizeof(example));
    

    这使得&amp;info[info-&gt;count] 仅在info-&gt;count=0 时有效,其余的你没有分配任何空间。

    【讨论】:

    • 谢谢你的断脚,效果很好。我忘了我还需要分配空间。
    • 很高兴能帮上忙。传统上,当您喜欢 ans 时,您会投票。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-24
    • 2012-09-19
    • 2023-04-07
    • 1970-01-01
    • 2014-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多