-1

I wanted to pass the reference for every element of the book array instead of passing the whole book array to the inputbook function. The program would exit after the first iteration, but I know that data for the first iteration already got pass to the struct array. can anyone explain why?

The struct:

struct {
    char *title ;
    int number ;
    int quantity ;
} typedef book ;

main function:

int main (){
    int i, lim = 0; 
    book book[MAX] ;
    
    while (1){
        printf("%d\n", lim);
        inputbook(&book[lim]) ;
        lim ++ ;
    }
    return 0 ;
}

inputbook function:

void inputbook(book* temp){
    printf("Title: ");
    scanf ("%s", (*temp).title);
    printf("Quantity: ");
    scanf ("%d", &(*temp).quantity) ;   
}
louisnot
  • 63
  • 5
  • 1
    Nothing to do with passing of the struct. `scanf ("%s", (*temp).title);` is wrong as `title` is an uninitalised pointer. – kaylum Jun 23 '21 at 07:15
  • Generally you write `typedef struct { ... } book;` Also, you cannot use any input function correctly unless you ***check the return***, e.g. `if (scanf ("%d", &temp->quantity) != 1) { /* handle error */ }`. – David C. Rankin Jun 23 '21 at 07:30
  • A better approach with full input validation [InputBooks](https://paste.opensuse.org/67640049) – David C. Rankin Jun 23 '21 at 08:09
  • `while(1)` will loop forever. if you want one iteration, just remove the loop completely. – Chef Gladiator Jun 23 '21 at 09:27

1 Answers1

3

You don't allocate memory for book.title.