c-为什么我的动态分配数组只包含一个结果



当我在linux机器上运行这段代码时,我注意到当我尝试迭代和存储各种用户输入的字符串时,它会导致整个数组只包含一个值。有人能帮我吗?

当我希望实际值放在我分配的数组中时,它似乎只保存buf的内存地址(从而为每个条目生成相同的字符串(。

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct
{
char *name;
} Task;

int main()
{
/*Allocate 5 sets of Task structs onto the heap. 
which we access   the starting address with our pointer*/

Task *my_list = malloc(sizeof(Task)*5);

/*user input*/
char buf[100]="";
/*loop through our allocated array and fill with user entered tasks*/
for(int i=0;i<5;i++)
{
printf("Enter task:t");
fgets(buf,99,stdin);
my_list[i].name = buf;
//bzero(buf,100);
}
/*now let's print the allocated array*/
for(int i=0;i<5;i++)
{
printf("%d:%sn",i,my_list[i].name);
}

/*now let's free the data*/
free(my_list);
return 0;
}

已解决。这是因为在我的结构中我有一个字符指针。而不是具有定义字节大小的静态分配数组。

您的问题是将name指针分配给内存中的单个已分配点(buf(。您需要使用strdup或类似方法创建新分配的内存位置。

IE,更改:

my_list[i].name = buf;

my_list[i].name = strdup(buf);

另一种选择是在结构中分配固定大小:

typedef struct
{
char name[100];
} Task;

然后直接读取:

fgets(my_list[i].name,99,stdin);

因此类Task中所有具有指针名称的ur对象都指向相同的地址,即&buf,因此您可以获得buf的最后更新值,因为所有*名称都指向同一地址(&buf(

int main()
{
/*Allocate 5 sets of Task structs onto the heap.
which we access   the starting address with our pointer*/
Task *my_list = (Task*)malloc(sizeof(Task)*5);

/*user input*/
//  char buf[100]="";
/*loop through our allocated array and fill with user entered tasks*/
for(int i=0;i<5;i++)
{
printf("Enter task:t");
char *buf=(char*)malloc(100);
fgets(buf,100,stdin);
my_list[i].name = buf;
//bzero(buf,100);
}
/*now let's print the allocated array*/
for(int i=0;i<5;i++)
{
printf("%d:%sn",i,my_list[i].name);
}

/*now let's free the data*/
free(my_list);
return 0;
}

相关内容

最新更新