I am trying to read from keyboard and store the info in my struct book. The user is asked to enter the array size and I dynamically allocate the size to my book array. But when n > 1, the run time error is exc_bad_access. I don't know why it works when n = 1 and it doesn't work when n > 1.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct book
{
char *title;
char *author;
double price;
};
int main()
{
int n, i = 0;
printf("please enter the value for n\n");
scanf("%d", &n);
struct book *stack = malloc(sizeof(struct book) * n);
stack->author = malloc(sizeof(char) * 100);
stack->title = malloc(sizeof(char) * 100);
//allocate memory for book and struct members
while (i < n )
{
printf("Please enter the title\n");
scanf("%s", stack[i].title);
printf("Please enter the author\n");
scanf("%s", stack[i].author);
printf("Please enter the price\n");
scanf("%lf", &stack[i].price);
i ++;
}
free(stack);
return 0;
}
sizeof (char)is redundant as it's1per definition.%sto prevent buffer overflow. Also you may need to reconsider the choice of input method if there are any books with multiple words in their title or author name!sizeof (char) * 100equals1 * 100equals100. So what is the need for usingsizeof (char)? Coding100would do the job.