C 不正确地打印链接列表中的字符串

C 不正确地打印链接列表中的字符串,c,linked-list,C,Linked List,这是我的密码 #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,

这是我的密码

#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;
    }
}
#包括
#包括
#包括
结构节点{
char-courseID[6];
int段;
国际学分;
结构节点*链接;
};
内部主(空)
{
int run=1;
charcoursetemp[6];
int选项,num,num2;
结构节点*ptr;
void add(结构节点**,int,int,char[]);
无效显示(结构节点*);
void del(结构节点*,int);
ptr=NULL;
while(run==1)
{
printf(“主菜单\n 1.添加课程\n2.删除课程\n3.显示注册课程\n”);
scanf(“%d”,选项(&O);
如果(选项==1)
{
printf(“请输入课程ID\n”);
scanf(“%s”,coursetemp);
printf(“请输入课程部分,以及其价值的学分金额”);
scanf(“%d%d”,&num,&num2);
添加(&ptr、num、num2、coursetemp);
显示器(ptr);
}
如果(选项==2)
{
printf(“输入要删除的元素\n”);
scanf(“%d”和&num);
del(ptr,num);
}
如果(选项==3)
{
显示器(ptr);
}
其他的
{
//printf(“请输入正确的选择\n”);
}//时间结束
}
返回0;
}  
无效显示(结构节点*pt)
{
while(pt!=NULL)
{
printf(“%s%d%d\n”,pt->courseID,pt->section,pt->credits);
pt=pt->link;
}
}

只要课程名称仅为字母,我就想这样做。但当我尝试使用字母和NUM(例如CIS444)时,我得到了一堆随机的ascii字符。我觉得这是一个简单的修复方法,但我不记得如何

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

无法复制,请添加中断程序的输入。如果字符串中有任何数字,它会输出错误的字符。(ex CIS120)
CIS120
长度为6个字符,对于
char[6]
而言,这一长度相当于6个字符,因为您需要保存终止符号。您至少需要
char[7]
+1:这似乎是问题所在,因为OP将
CIS120
作为示例输入。