0

How to make stack in c, program doesn't output all entered strings only the last what's happening? 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;
}
1
  • Please give examples of the expected vs actual behavior Commented Feb 27, 2018 at 20:41

1 Answer 1

1
setter(&aza->next, number);

This is the source of problem - where does next point to? 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. You can use malloc to allocate memory and make this struct instance's next point to it.

To help you a bit the changes would be:-

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

And also inprintBooks because scanf expects a char* not char (*)[] and also the function printBooks is supposed to take a 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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.