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

标签 c arrays

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

    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/

相关文章:

c - 将除\r 之外的所有字符添加到新字符串

c - 枚举 C 中的所有枚举名称/值

php - 从 laravel 中的数据库动态填充语言翻译数组

c++ - 可视化抽象树的工具

GetOpenFileName 能否将文件选择限制为与过滤器匹配的文件?

javascript - 在javascript中获取矩阵的所有可能选项

arrays - 将阈值应用于数组中的所有值

c - 如何修复 "format specifies type ' char *' but the argument has type ' char * *'"错误

在 C 中使用动态数组创建对象/typedef 结构

c - 常量变量的定义与#define