the task is to dynamically allocate memory for the array of structures and then fill them from keyboard. I was able to dynamically allocate and fill amount of pages for each of the struct instance in array, but when I try to add char* to it by doing something like:
strcpy(myArray[i]->author, authorName);
But every time I get segmentation error, so what am I doing wrong? Is it possible that problem is actually in memory allocation?
Here is the code
#include <stdlib.h>
#include <string.h>
struct Book {
char* author;
char* title;
int pages;
int pubYear;
int copies;
};
void allocList(struct Book **myArray, int booksAmount);
void fillKeyboard(struct Book **myArray, int booksAmount);
int main(void) {
struct Book *booksList = NULL;
int booksAmount = 3;
allocList(&booksList, booksAmount);
fillKeyboard(&booksList, booksAmount);
return 0;
}
void allocList(struct Book **myArray, int booksAmount) {
*myArray = (struct Book*) malloc(sizeof(struct Book) * 100);
printf("memory for %d books was allocated \n", booksAmount);
}
void fillKeyboard(struct Book **myArray, int booksAmount) {
int i = 0;
char* authorName = "author name";
while (booksAmount--) {
printf("book number %d \n", i + 1);
printf("enter amount of pages: ");
scanf("%d", &(*myArray)[i].pages);
printf("\nenter author: ");
strcpy(myArray[i]->author, authorName);
printf("%s is \n", authorName);
i++;
printf("\n");
}
}
Thank you.