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

时间:2011-12-15 05:15:14

标签: c arrays

我正在制作对象的链接列表。出于某种原因,当我打印对象(char数组)中的值的值时,我会在值之前进行垃圾打印。为什么会发生这种情况,我该如何摆脱它呢?这是我的代码的一部分:

    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);
}

3 个答案:

答案 0 :(得分:1)

初始节点中的char数组未初始化。变化

llist->data1[100] = NULL;

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

阻止它被打印。

答案 1 :(得分:1)

这两行一起是错误的:

char avalue[100] = ""; 
[...]
scanf("%s", &avalue);

scanf字符串的正确方法是:

scanf("%s", avalue);  // No Address-Of operator.

答案 2 :(得分:0)

您的代码的重要部分(基于您对问题的描述)可以归结为:

struct PDB2 {
    char data[100];
    ...other fields...
};

struct PDB2 * llist = (struct PDB2 *)(malloc(sizeof(struct PDB2)));

llist->data[100] = NULL; /* This is wrong */

printf("%s", llist->data); /* This prints rubbish */

标记的行是错误的,因为:

  1. NULL用作指针值,而不是字符。您可能想要使用'\0'
  2. 关键似乎是清除字符串,所以正确的方法是
  3. llist->data[0] = '\0';
    

    此外,对scanf的调用似乎应该是

    char avalue[100];
    
    scanf("%s", avalue);
    

    因为avalue已经是char *类型。使用额外的&,您可能会写入无效的位置。然而,

    int input;
    
    scanf("%d", &input);
    

    对于整数输入是正确的。