-1
I have the following code in C:
#include <stdio.h>
#include <stdlib.h>
struct pessoa{
char nome[11];
int idade;
}
void cadastra_pessoa(char novo_nome[11], int nova_idade, struct pessoa *vetor_pessoas, int *quantidade)
{
vetor_pessoa = realloc(vetor_pessoa, sizeof(struct pessoa) * (++(*quantidade)));
strcpy(vetor_pessoa[(*quantidade) - 1].nome, novo_nome);
vetor_pessoa[(*quantidade) - 1].idade = nova_idade;
int main()
{
int quantidade_de_pessoas = 0;
struct pessoa *vetor_pessoas = NULL;
cadastra_pessoa("Robson", 12, vetor_pessoas, &quantidade_de_pessoas);
cadastra_pessoa("Joao", 31, vetor_pessoas, &quantidade_de_pessoas);
cadastra_pessoa("Ana", 19, vetor_pessoas, &quantidade_de_pessoas);
return 0;
}
Whose goal is to dynamically increase the size of the people vector (a pointer to struct) every time a person registers. However, the code within the function cadastra_pessoa(), that should increase the size of the vector by 1 unit at each call and add a person to the last position, it just doesn’t work... the only part that works is the increment of the variable pointed by the pointer quantidade! Interestingly, the same code works fully when it is put out of a function, directly within the main(). Why only inside the function does not work? I should, within the function, access the members of the struct differently or this task is not possible to do through functions?