简体   繁体   English

在c中排队我的代码或算法中有一些问题?

[英]queue in c Some problems in my code or algorithm?

How to make stack in c, program doesn't output all entered strings only the last what's happening? 如何在c中制作堆栈,程序不会仅输出最后输入的所有字符串? Don't know what to write but website asks to write something, argues that there isn's any explanations. 不知道该写些什么,但网站要求写点东西,认为有任何解释。 When I want to print all books with the help of link to their next book, but it's only outputting the last entered thing. 当我想借助所有下一本书的链接打印所有书籍时,它仅输出最后输入的内容。 Is it overwriting? 是否覆盖?

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

typedef struct book book;

struct book{
    book *next;
    char name[100];
    int year;
    char author[100];
};

void setter(book *aza, int number){
    char name[100];
    int year;
    char author[100];

    scanf("%s", name);
    scanf(" %d", &year);
    scanf("%s", author);

    strcpy( aza->name , name );
    aza->year = year;
    strcpy( aza->author, author );

    number--;

    if(number==0){
        return;
    }else{
        setter(&aza->next, number);
    }
}

printBooks(book *aza){
    if(aza){
         printf("%s\n", &aza->name);
         printBooks(&aza->next);
    }
}

int main()
{
    book kitap;
    int number;

    scanf("%d", &number);
    setter(&kitap, number);
    printBooks(&kitap);

    return 0;
}
setter(&aza->next, number);

This is the source of problem - where does next point to? 这就是问题的根源- next指向哪里? It contains some garbage value pointing nowhere. 它包含一些无处指向的垃圾值。 It is undefined behavior trying to access it. 尝试访问它是未定义的行为。 That is what you did exactly. 那就是你所做的。

Allocate memory and pass it to setter - other wise it is trying to access some random memory and trying to set values in it. 分配内存并将其传递给setter-否则,它将尝试访问一些随机内存并尝试在其中设置值。 You can use malloc to allocate memory and make this struct instance's next point to it. 您可以使用malloc分配内存,并使该结构实例的next指向它。

To help you a bit the changes would be:- 为了帮助您一点更改:

    aza->next = malloc(sizeof *(aza->next));
    setter(aza->next, number);

And also in printBooks because scanf expects a char* not char (*)[] and also the function printBooks is supposed to take a book* . 以及在printBooks因为scanf期望的是char*而不是char (*)[] ,并且函数printBooks应该采用book*

     printf("%s\n", aza->name);
     printBooks(aza->next);

Illustration using some code - here . 使用一些代码的插图- 在此处 Also you need to write the function for freeing all these memories except the first structure instance. 另外,您还需要编写用于释放除第一个结构实例之外的所有这些内存的函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM