Reputation: 175
I have made this program to save the information about a book but it doesn't print it correctly
#include <stdio.h>
enum Color {red, green, blue};
struct Book{
int pages;
char* author;
char* title;
enum Color color;
};
void getInfo(struct Book book){
book.pages= 200;
book.author = "Cervantes";
book.title= "El Quijote";
book.color = green;
}
void showInfo(struct Book book){
printf("pages: %d\n", book.pages);
printf("author: %s\n", book.author);
printf("title: %s\n", book.title);
switch (book.color) {
case red:
printf("Color: red\n");
break;
case green:
printf("Color: green\n");
break;
case blue:
printf("Color: blue\n");
break;
}
}
int main(){
struct Book book1;
getInfo(book1);
showInfo(book1);
return 0;
}
In principle, the program should save them well, because if I put the print inside the function where the data is saved, they do print correctly. But by modularizing the program, it stops doing it.
Upvotes: 0
Views: 285
Reputation: 212634
C is pass by value, so any changes made to a parameter are local to the function. If you want to change the value in the caller, you need to pass an address. eg:
#include <stdio.h>
enum Color {red, green, blue};
char *colornames[] = { "red", "green", "blue" };
struct Book {
int pages;
char *author;
char *title;
enum Color color;
};
void
getInfo(struct Book *book)
{
book->pages= 200;
book->author = "Cervantes";
book->title= "El Quijote";
book->color = green;
};
void
showInfo(const struct Book *book)
{
printf("pages: %d\n", book->pages);
printf("author: %s\n", book->author);
printf("title: %s\n", book->title);
printf("color: %s\n", colornames[book->color]);
}
int
main(void)
{
struct Book book1;
getInfo(&book1);
showInfo(&book1);
return 0;
}
Upvotes: 4