I want to allocate memory for "title" dynamically as I don't know how long the titles will be. I have the following code:
#include<stdio.h>
#include<malloc.h>
struct film {
char title[500];
int year;
int duration;
int earnings;
};
void main() {
int n;
scanf("%d", &n);
int array[n], i = 0;
struct film user[n];
while (i < n) {
scanf("%s", &user[i].title);
scanf("%d", &user[i].year);
scanf("%d", &user[i].duration);
scanf("%d", &user[i].earnings);
i += 1;
}
}
I tried replacing:
char title[500];
with:
char *title = (char*)malloc(sizeof(char));
However, it didn't work. It says that it expects something else before "=". Also, how do I scanf the input from the user for title if it is dynamically allocated?
How do I free the memory later? I assume it's as below:
void freememory(struct film target, n) { //n is size of structure
int i = 0;
while (i < n) {
free(target[i].title);
i += 1;
}
Correct?