My question is: am I allocating the array correctly?
Not at all. The allocation was done based on the DIRETOR
size, allocating a DIRETORES
vector but the filme
type is char**
:
diretor[i].filme = (char **) malloc(sizeof(DIRETOR) * diretor[i].qtd);
// ^---- tipo ^---- tamanho alocado de cada elemento
In other words, it has allocated a vector of directors and saved it in a double char pointer, so the types and sizes do not play. If your array is an array of char**
to save strings declared as char **filme
then the correct allocation would be:
diretor[i].filme = malloc(sizeof(char *) * diretor[i].qtd);
// ^----
Note that I omitted cast because it is not required. I should also add that calling the filmes
field would be much brighter than it represents, instead of filme
.
But I can not help saying that this does not answer the statement. The statement clearly states that:
Each movie consists of name, year and duration
Then filme
should be a structure:
typedef struct filme {
char nome[50];
int ano, duracao;
} FILME;
And now this would be the structure used within DIRETOR
:
typedef struct diretor {
char nome[20];
FILME *filmes; // <--- vetor dinâmico de filmes
int qtd;
} DIRETOR;
The allocation would now be:
diretor[i].filmes = malloc(sizeof(FILME) * diretor[i].qtd);
Now it's not enough to adjust the remaining code for this new movie structure.