【问题标题】:incorrectly printing string in linked list在链表中错误地打印字符串
【发布时间】:2013-03-28 20:51:16
【问题描述】:

这是我的代码

#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 字符。我觉得这是一个简单的修复,但我不记得如何

【问题讨论】:

  • 无法重现,请添加破坏程序的输入。
  • 如果字符串中有任何数字,它会打印出错误的字符。 (前 CIS120)
  • CIS120 的长度为 6 个字符,对于 char[6] 来说太大了,因为您需要保存终止符号。你至少需要char[7]

标签: c linked-list


【解决方案1】:

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

【讨论】:

  • +1:这似乎是问题所在,因为 OP 声明 CIS120 作为示例输入。
猜你喜欢
  • 2021-12-18
  • 1970-01-01
  • 2021-10-23
  • 1970-01-01
  • 2012-10-18
  • 1970-01-01
  • 1970-01-01
  • 2021-05-25
  • 1970-01-01
相关资源
最近更新 更多