帮助我,我只是一个新手。
我目前正在C学习和练习链表。我想根据它们的大小来安排乐器的名称。
问题是,每次创建新乐器时,我新创建的乐器都会覆盖以前乐器的名称,但不会覆盖尺寸。
为什么以及在那里发生了什么?
例如,第一个乐器是" FLUTE"和大小为1,它将显示这些信息。但是当第二个循环到来并且我输入第二个乐器时,名字是" TRUMPET"和大小是3," FLUTE"走了..!它会显示名称:TRUMPET,大小:1 //但大小仍在那里。
名称:TRUMPET,大小:3
//here's my main
int main(void)
{
int add = 1;
int size;
char name[30];
instrument *start = NULL;
instrument *x = NULL;
instrument *y = NULL;
instrument *next = NULL;
while(add != 0)
{
printf("Enter the name of the instrument: ");
scanf(" %29s", name);
printf("Size: ");
scanf(" %d", &size);
next = pos(name, size);
if(start == NULL)
{
start = next;
}
if(x != NULL)
{
x->next = next;
}
x = next;
//for now, I'll just display the instruments instead of sorting them.
displayInstruments(start);
printf("\nDo you want to add more?: ");
scanf(" %d", &add);
}
freeInstruments(start);
return 0;
}
//this is my instrument creator function
instrument* pos(char *name, int size)
{
instrument *i = malloc(sizeof(instrument));
i->name = name;
i->size = size;
i->next = NULL;
return i;
}
//and other codes below here that don't matter for now. . . . . . . .
.
.
.
.
答案 0 :(得分:2)
您为每个instrument
创建空间,但为每个名称使用相同的空格(全局变量name
)。
答案 1 :(得分:1)
您正在使用单个缓冲区来存储每个乐器的name
。默认情况下,将复制int
s,以便您正确存储每个乐器的大小。但是,对于字符串,您存储一个指针,该指针保存字符串的内存位置。所有instrument->name
指针都指向相同的内存位置,因此它们都会显示最近添加的乐器名称。
要解决此问题,请将i->name = name
更改为i->name = strdup(name)
,这将复制字符串并创建自己的个人副本。