2013-03-28 164 views
0

这里是我的代码链表中不正确打印字符串

#include<stdio.h> 
#include<stdlib.h> 
#include<string.h> 

struct node { 
    char courseID[6]; 
    int section; 
    int credits; 
    struct node *link; 
}; 

int main(void) 
{ 
    int run=1; 
    char coursetemp[6]; 
    int option, num, num2; 
    struct node *ptr; 
    void add(struct node **, int, int, char[]); 
    void display(struct node *); 
    void del(struct node *, int); 

    ptr = NULL; 
    while (run==1) 
    { 
     printf("Main Menu\n 1. Add Course\n2.Delete Course\n3. Display Enrolled courses\n"); 
     scanf("%d", &option); 
     if (option == 1) 
     { 
      printf("Please enter the course ID\n"); 
      scanf("%s", coursetemp); 
      printf("Please enter the course section, and amount of credits it's worth\n"); 
      scanf("%d %d", &num, &num2); 
      add(&ptr, num, num2, coursetemp); 
      display(ptr); 
     } 
     if (option == 2) 
     { 
      printf("Enter the element to delete\n"); 
      scanf("%d", &num); 
      del(ptr, num); 
     } 
     if (option == 3) 
     { 
      display(ptr); 
     } 
     else 
     { 
      //printf("Please enter a proper selection\n"); 
     } //end of while 
    } 
    return 0; 
} 
void display(struct node *pt) 
{ 
    while (pt != NULL) 
    { 
     printf("%s %d %d\n", pt->courseID, pt->section, pt->credits); 
     pt = pt->link; 
    } 
} 

这个工程,我想让它,只要课程名称只是字母。但是,只要我尝试用字母和数字前例。 CIS444我得到一堆随机的ascii字符。我觉得这是一个简单的修复,但我不记得如何

+1

无法重现,请添加破坏您的程序的输入。 – Zeta

+0

如果字符串中有任何数字,则会打印出错误的字符。 (ex CIS120) – trev

+0

由于您需要保存终止符号,因此'CIS120'长度为6个字符,由char [6]长为大。你至少需要'char [7]'。 – Zeta

回答

1

我怀疑是你输入的课程ID为6或更多的字符。 courseID成员最终只能使用空终止符保存5个字符的ID。例如,如果您输入了6个字符的课程ID,则它会将7个字节复制到courseID中,并根据结构对齐方式覆盖结构中以下成员的一部分。请注意,在这种情况下,变量coursetemp也将被写入结尾(导致未定义的行为)。

+0

+1:这似乎是问题,因为OP声明'CIS120'作为示例输入。 – Zeta

+0

@泽塔:这次精神调试工作! ;) –