gpt4 book ai didi

C 编程为什么在值之前打印垃圾?

转载 作者:行者123 更新时间:2023-11-30 14:26:48 24 4
gpt4 key购买 nike

我正在创建一个对象的链接列表。由于某种原因,当我去打印对象(字符数组)内的值的值时,我在该值之前得到垃圾打印。为什么会发生这种情况以及如何摆脱它?这是我的代码的一部分:

    int num = 0;
int input = 1;
int retval = 0;
struct PDB2 *llist;
char avalue[100] = "";
llist = (struct PDB2 *)malloc(sizeof(struct PDB2));
llist->data1[100] = NULL;
llist->next = NULL;

while(input != 0) {
printf("\n-- Menu Selection --\n");
printf("0) Quit\n");
printf("1) Insert\n");
printf("2) Delete\n");
printf("3) Search\n");
printf("4) Display\n");
scanf("%d", &input);

switch(input) {
case 0:
default:
printf("Goodbye ...\n");
input = 0;
break;
case 1:
printf("Your choice: `Insertion'\n");
printf("Enter the value which should be inserted: ");

scanf("%s", &avalue);
append_node(llist, avalue);
break;
case 2:
printf("Your choice: `Deletion'\n");
printf("Enter the value which should be deleted: ");
scanf("%s", &avalue);
delete_node(llist, avalue);
break;
case 3:
printf("Your choice: `Search'\n");
printf("Enter the value you want to find: ");
scanf("%s", &avalue);
if((retval = search_value(llist, avalue)) == -1)
printf("Value `%s' not found\n", avalue);
else
printf("Value `%s' located at position `%d'\n", avalue, retval);
break;
case 4:
printf("You choice: `Display'\n");
display_list(llist);
break;
} /* switch */
} /* while */

free(llist);
return(0);
}


void append_node(struct PDB2 *llist, char message[])
{
int x = 0;
while(llist->next != NULL)
{
llist = llist->next;
}

llist->next = (struct PDB2 *)malloc(sizeof(struct PDB2));

for(x = 0; x < 100; x++)
{
llist->next->data1[x] = message[x];
}
llist->next->next = NULL;

}
void display_list(struct PDB2 *llist)
{
while(llist->data1 == NULL)
{
llist = llist->next;
}
while(llist->next != NULL)
{
printf("%s ", llist->data1);
llist = llist->next;
}
printf("%s", llist->data1);
}

最佳答案

初始节点中的字符数组未初始化。改变

llist->data1[100] = NULL;

llist->data1[0] = '\0';

阻止其被打印。

关于C 编程为什么在值之前打印垃圾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8515435/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com