Reputation:
I created a struct Book with the properties.I let the user to create the structure objects with for-loop.Like Books[i] Books1, Books2 etc...
The problem is that i cant store integer values in the structure.
The code is given below.
#include <stdlib.h>
#include <stdio.h>
struct Book {
int ID[];
char book_name[80];
char author_name[50];
int pblsh_date[];
};
struct Book *Books;
void Create();
int main() {
int count;
printf("How many books do you want to enter? ");
scanf("%d", &count);
Create(count);
//Show
printf("ID\t\tName\tAuthor\tPublish Year\n");
for (int i= 0; i < count; i++)
printf("%d\t%s\t%s\t%d\n", Books[i].ID, Books[i].book_name, Books[i].author_name, Books[i].pblsh_date);
if (Books) {
free(Books);
}
getchar();
return 0;
}
void Create(int count) {
Books = (struct Book*) malloc(count * sizeof(struct Book));
int i;
for (i = 0; i < count; i++) {
printf("%d. Book's ID: ", i+1);
scanf("%d", Books[i].ID);
printf("Book's name: ");
scanf("%s", Books[i].book_name);
printf("Author: ");
scanf("%s", Books[i].author_name);
printf("Publish Year: ");
scanf("%d", Books[i].pblsh_date);
}
}
Upvotes: 0
Views: 98
Reputation: 114460
The definition of the structure that you posted contains two empty arrays: int ID[];
and int pblsh_date[];
. Since you did not specify a size and the compiler is not throwing an error, it is not allocating any storage for the array data: the arrays are zero-length and you are overwriting the data that follows them when you scanf
into them.
Since you only want a single integer, the correct way to define the structure is
struct Book {
int ID;
char book_name[80];
char author_name[50];
int pblsh_date;
};
The only other change you need to make to your program is the arguments to scanf
: scanf("%d", &(Books[i].ID));
and scanf("%d", &(Books[i].pblsh_date));
. The reason is that scanf
requires the address of the place you want to put the result. While scanf("%s", Books[i].book_name);
works as is, you need to add the &
operator to int
variables. book_name
is an array, which in C is treated as a pointer containing the address of the buffer you want to write to. ID
is an int, so you need to get its address to know where to write to. Notice how you already did this in main
with scanf("%d", &count);
.
Upvotes: 2