I'm learning about C and having trouble with this. It does compile but the result is unexpected. In my code, I have a struct:
typedef struct {
char *title[50];
float price;
} Book;
In the main, I am asking the user for number of books they want to have in the library. Then let them initialize the attributes of each book.
Finally, print them out to the terminal using Display function.
void Display(Book* lib, int n);
int main() {
int n;
printf("Enter the number of books:\n" );
scanf("%d", &n);
if(n <= 0) {
printf("Invalid number of book.");
return 1;
}
Book *lib = (Book *) malloc(n * sizeof(Book));
if(lib == NULL) {
printf("The memory is full");
return 1;
}
for(int i = 0; i < n; ++i) {
char title[50];
float price;
printf("Book no.%d\n", i);
printf("Book Title: ");
scanf("%s", title);
printf("Book Price: ");
scanf("%f", &price);
printf("\n");
*(lib+i)->title = title;
(lib+i)->price = price;
}
Display(lib, n);
return 0;
}
The code compiles successfully, but the result is like this:
Enter the number of books:
2
Book no.0
Book Title: AAAA
Book Price: 1.0
Book no.1
Book Title: BBBB
Book Price: 9.9
----Displaying----
Book no.0
Book Title: BBBB
Book Price: $1.000000
Book no.1
Book Title: BBBB
Book Price: $9.900000
The title of the first book is wrong and it is the title of the second book. Why does this happen? And how should I fix it? Thank you
Edit: One of the requirements in my assignment is the title of Book must be of type char*
Edit 2: I realized my mistake when having 50 pointers of type char now. How should I fix it?
char *title[50];that's not a string pointer; that's 50 string pointers.char *title[50]. Should I allocate it by malloc?char title[50];at all. you have allocated in the heap scanf to the heap no need for this char array and fix the title to be char title[50 not char* title[50] in the struct definitiontitleof typechar*is actually one of the requirements in my assignment.