Search code examples
cfunctionstructprintfgarbage

Hard time printing struct members with a function


I'm new to C and I'm developing this basic project while I study it, to help me fixate things... so please, bear with me if my code still looks kind of stupid.

That being said, I'm having trouble with a function to print struct members. I've created a function to register book details and a separate one for printing said details.

If I print the details within the registerBook function, they are printed correctly.

However, when I call the method printBook, all I get is "garbage". And it's always the same characters,

The code is as follows:


#include <stdio.h>
#include <stdlib.h>

struct Books {
    char title[30];
    char author[20];
    int book_id[10];
    char subject[50];
} Books;

int main() {

    struct Books Book1;
    struct Books Book2;

    registerBook(Book1);
    printBook(Book1);
    registerBook(Book2);
    printBook(Book2);

    int exit = 0;
    while(exit == 0) {
        scanf("%p", exit);
    }

    return 0;
}

void printBook(struct Books a){
    printf("\nTitle: %s", a.title);
    printf("\nAuthor: %s", a.author);
    printf("\nISBN: %d", a.book_id);
    printf("\nSubject: %s", a.subject);
}

void registerBook(struct Books a){
    printf("\nTitle?");
    scanf("%s", &a.title);
    printf("\nAuthor?");
    scanf("%s", &a.author);
    printf("\nISBN?");
    scanf("%d", &a.book_id);
    printf("\nSubject?");
    scanf("%s", &a.subject);
}

All I get is:


Title?one

Author?two

ISBN?3

Subject?four

Title: ç Author: ` ISBN: 6356340 Subject: Ç@ Title?five

Author?six

ISBN?7

Subject?eight

Title: &Ý=w¬8wÝ=wÃÊpï Author: ISBN: 6356340 Subject:


Could someone please advise?


Solution

  • In the registerBook function you should pass the parameters by reference and not by value so you can keep the changes after the function ends.

    #include <stdio.h>
    #include <stdlib.h>
    
    struct Books {
        char title[30];
        char author[20];
        int book_id;
        char subject[50];
    } Books;
    
    void printBook(struct Books a){
        printf("\nTitle: %s", a.title);
        printf("\nAuthor: %s", a.author);
        printf("\nISBN: %d", a.book_id);
        printf("\nSubject: %s", a.subject);
    }
    
    void registerBook(struct Books* a){
        printf("\nTitle?");
        scanf(" %s", a->title);
        printf("\nAuthor?");
        scanf(" %s", a->author);
        printf("\nISBN?");
        scanf(" %d", &a->book_id);
        printf("\nSubject?");
        scanf(" %s", a->subject);
    }
    
    
    
    int main() {
    
        struct Books Book1;
        struct Books Book2;
    
        registerBook(&Book1);
        printBook(Book1);
        registerBook(&Book2);
        printBook(Book2);
    
    
        return 0;
    }
    

    I didn't include your exit loop as it is something that has nothing to do with your problem here.