You have several problems
you missed to allocate your instance of book
&ptr->title[100]
is invalid
the use of gets is deprecated since years, use fgets to limit the size and avoid undefined behavior
you missed to check your scanf return 1 to know if a valid input was done
you have a memory leak because of the malloc without a free, and in fact you do not need to allocate your book in the heap
are you sure just a char is enough for authors ? probably you wanted an array
gets(&ptr->authors);
is invalid because authors is just a character
the format "%s" for authors is invalid because it is just a character
you missed a % before "lf" to print the price
Probably you do not want the newline in the input string
You wanted something like :
#include<stdio.h>
#include <stdlib.h>
#include <string.h>
struct book {
char title[100];
char authors[100];
int code;
double prc;
};
int main(void) {
struct book * ptr = malloc(sizeof(struct book));
size_t len;
printf("Title:\n");
if (fgets(ptr->title, sizeof(ptr->title), stdin) == NULL)
/* EOF */
return -1; /* or an other behavior is you want */
len = strlen(ptr->title);
if (ptr->title[len - 1] == '\n')
ptr->title[len - 1] = 0;
printf("authors:\n");
if (fgets(ptr->authors, sizeof(ptr->authors), stdin) == NULL)
/* EOF */
return -1;/* or an other behavior is you want */
len = strlen(ptr->authors);
if (ptr->authors[len - 1] == '\n')
ptr->authors[len - 1] = 0;
printf("code:\n");
if (scanf("%d",&ptr->code) != 1) {
puts("invalid code");
return 1; /* or an other behavior is you want */
}
printf("Price:\n");
if (scanf("%lf",&ptr->prc) != 1) {
puts("invalid price");
return 1; /* or an other behavior is you want */
}
printf("T:%s,A:%s,C:%d,P:%lf\n",ptr->title,ptr->authors,ptr->code,ptr->prc);
free(ptr);
return 0;
}
or without allocating the book in the heap :
#include<stdio.h>
#include <string.h>
struct book {
char title[100];
char authors[100];
int code;
double prc;
};
int main(void) {
struct book b;
size_t len;
printf("Title:\n");
if (fgets(b.title, sizeof(b.title), stdin) == NULL)
/* EOF */
return -1; /* or an other behavior is you want */
len = strlen(b.title);
if (b.title[len - 1] == '\n')
b.title[len - 1] = 0;
printf("authors:\n");
if (fgets(b.authors, sizeof(b.authors), stdin) == NULL)
/* EOF */
return -1;/* or an other behavior is you want */
len = strlen(b.authors);
if (b.authors[len - 1] == '\n')
b.authors[len - 1] = 0;
printf("code:\n");
if (scanf("%d",&b.code) != 1) {
puts("invalid code");
return 1; /* or an other behavior is you want */
}
printf("Price:\n");
if (scanf("%lf",&b.prc) != 1) {
puts("invalid price");
return 1; /* or an other behavior is you want */
}
printf("T:%s,A:%s,C:%d,P:%lf\n",b.title,b.authors,b.code,b.prc);
return 0;
}
Compilation and execution :
pi@raspberrypi:/tmp $ gcc -pedantic -Wall -Wextra c.c
pi@raspberrypi:/tmp $ ./a.out
Title:
the mirific title
authors:
me
code:
007
Price:
12.34
T:the mirific title,A:me,C:7,P:12.340000
pi@raspberrypi:/tmp $