【问题标题】:Inputting errors in structure pointer code在结构指针代码中输入错误
【发布时间】:2021-06-15 11:42:06
【问题描述】:
 #include <stdio.h>
typedef struct book
{
    int bid;
    char bname[50];
} bok;
typedef struct student
{
    int roll;
    char sec;
    char name[50];
    bok *issue;
} stud;

int main()
{
    int n;
    printf("enter no. of students\n");
    scanf("%d", &n);
    stud s[n];
    printf("enter names,section and roll no. of %d students\n", n);
    for (int i = 0; i < n; i++)
    {
        scanf("%s", &s[i].name);
        scanf("%c", &s[i].sec);
        scanf("%d", &s[i].roll);
    }
    int m, temp;
    printf("enter no. of books\n");
    scanf("%d", &m);
    bok s1[m];
    printf("enter book id and book names of %d books\n", m);
    for (int i = 0; i < m; i++)
    {
        scanf("%d\n", &s1[i].bid);
        scanf("%s\n", &s1[i].bname);
    }
    printf("assign book id to students.\n");
    for (int i = 0; i < n; i++)
    {
        printf("assign id for roll %d\n", s[i].roll);
        scanf("%d\n", s[i].issue);
    }
    int info;
    printf("enter roll no. of student to get his/her information and book assigned to him\n ");
    scanf("%d\n", &info);
    for (int i = 0; i < n; i++)
    {

        if (s[i].sec == info)
            printf("name:%s \nsection:%c \nbook assigned:%s\n", s[i].name, s[i].sec, *s[i].issue);
    }
}

我的代码没有显示任何编译错误,但它没有给出所需的输出。我的问题是创建 2 个两个结构数组 Student 和 Book,名称为 S 和 B。并将学生与各自的书链接起来。 打印特定学生发行的书籍。

【问题讨论】:

    标签: arrays c pointers structure


    【解决方案1】:

    不要忘记括号,以便将用户的输入分配给相应的结构成员:

    for (int i = 0; i < n; i++)
    {
        scanf("%s", &(s[i].name));
        scanf("%c", &(s[i].sec));
        scanf("%d", &(s[i].roll));
    }
    

    这里你需要将输入分配给bid,你不能为book设置一个整数:

    scanf("%d\n", &(s[i]->issue.bid));
    

    否则你会得到一个段错误。

    【讨论】:

    • 感谢您的回答 antonin 但它没有用:'(
    猜你喜欢
    • 1970-01-01
    • 2014-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-17
    • 2018-07-12
    • 2017-03-16
    相关资源
    最近更新 更多