relationship between struct array & malloc
Code:
#include <stdlib.h>
#include <stdio.h>
#define STR_LENGTH 30
void memoryAlloc (int a);
void display(struct book_info* a, int count);
struct book_info {
char author[STR_LENGTH];
char title[STR_LENGTH];
char pg[STR_LENGTH];
};
int main(int argc, char* argv[])
{
int count;
int i;
fputs("Pease enter how many book to record: ",stdout);
scanf("%d",&count);
memoryAlloc(count);
fflush(stdin);
struct book_info* bookArray[count]; //variable cannot put in
for (i = 0; i < count; ++i){
printf("Book %d\n",i+1);
fputs("Name of Author: ",stdout);
fgets(bookArray[i].author,STR_LENGTH,stdin);
fflush(stdin);
fputs("Title of the Book:",stdout);
fgets(bookArray[i].title,STR_LENGTH,stdin);
fflush(stdin);
fputs("Number of Page: ",stdout);
fgets(bookArray[i].pg,STR_LENGTH,stdin);
fflush(stdin);
}
display(bookArray, count);
free(bookArray);
return 0;
}
void display(struct book_info* a, int count){
int i;
for (i = 0; i < count; ++i){
printf("Book %d\n",i+1);
fputs("-----------------------------",stdout);
printf("Name of Author: %s",a[i].author);
printf("Title of the Book: %s",a[i].title);
printf("Number of Page: %s",a[i].pg);
fputs("-----------------------------",stdout);
}
}
//dynamic memory allocation function
void memoryAlloc (int a){
int* arr;
arr = (int*)malloc(a * sizeof(int));
if (a == NULL){
fputs("Filed to allocate memory!!!",stdout);
exit(1);
}
}
Hey guys, It might be a dumb question, but I really need your help.
I'm trying to get a number from a user and then create an array with the number of index the user put in.
For example, if a user input 3, array[3] will be created.
I know that "int array[count]" won't work because a variable cannot be put in.
So I made a function that allocates dynamic memory.
However, I can't link it with struct.
Anyone can give me a solution?