MrKaszu
MrKaszu

Reputation: 71

C passing string between functions

I'm writing simple program in C and got stucked. I have three functions:

void changeStatusOfBook(User users[], Book books[]) {
  char *id= askForBookID();
  Book book = getBookById(books, id);
  .
  .
  .
}

char * askForBookID() {
  char id[6];
  printf("Tell me which book (ID)\n");
  scanf_s("%5s",id, 6);
  return id;
}

Book getBookById(Book books[], char bookID[]) {
  int counter = 0;
  //bookID becomes a trash here
  .
  .
  .
}

The problem is: In the first function I get correct user string input, but when I pass it to third function I'm getting some trash in it. How to fix it?

Upvotes: 0

Views: 365

Answers (2)

Seek Addo
Seek Addo

Reputation: 1903

You can't return a local variable char id[] from a function.It's memory is on the stack and when the function returns all stack memory for that function and its local variables are no more accessible.

when memory is need on the stack for another program it overrides the memory space for char id, and this becomes a problem for your program.

 char * askForBookID() {
      //char id[6];
        char *id = malloc(sizeof(char)*6);
        if(!id){ //check if malloc got some memory for id
           printf("Sorry not enough memory"); return NULL;

         }

       printf("Tell me which book (ID)\n");
       scanf_s("%5s",id, 6);

       return id;
}

Upvotes: 3

Bathsheba
Bathsheba

Reputation: 234875

The function askForBookID returns the address of the first element of an array with automatic storage duration.

The behaviour on your using that pointer oncce the function has been called is undefined.

Use malloc instead.

Upvotes: 3

Related Questions