0
Guys, how do I allocate one structure whenever the user wants to allocate another one? How do I make this increment? I’m putting a code here just so you can understand my problem.
#include <stdio.h>
#include <stdlib.h>
/*
SÍNTESE
OBJETIVO: Calcular bônus de funcionário com mais de 10 anos de serviço
ENTRADA: Nome do funcionário, nome do departamento salário, salário e tempo de serviço
SAÍDA: Nome do funcionário, nome do departamento, salário com bônus ou nao, e tempo de serviço, se deseja continuar
*/
#define MAX_FUNCIONARIOS 5
#define MAX_NOME 100
typedef struct{
char nome[MAX_NOME];
char nomeDepartamento[MAX_NOME];
float salario;
int tempoServico;
}Funcionarios;
int main(int argc, char *argv[]) {
int numEstruturas=0, opcao=0;
do{
//aloca dados para um vetor de estruturas
func = (Funcionarios*) malloc(1*sizeof(Funcionarios));
//verifica se a alocacao ocorreu corretamente
if(!func){
printf("\nNao foi possivel alocar espaco para esta estrutura!\n");
exit(0);
}
printf("Deseja adicionar outra estrutura: (1) ou (2)-sair");
scanf("%d", &opcao);
if(opcao == 1){
func = (Funcionarios*) realloc(numEstruturas*sizeof(Funcionarios));
}else{
break;
}
}while(opcao==1&&n<MAX_FUNCIONARIOS);
return 0;
}
You need to use a vector or a list of employees and go adding employees. But both a solution and a solution are still missing a lot in your code. I suggest you start your searches there.
– Isac
It’s just an example. I just wanted to know if it’s correct the way I’m relocating the data or if I’m at least close.
– Lucas Correia
The relocation with the
realloc
will make sense if you have an employee vector that wants to increase as you enter. In this sense yes this will be the way, assuming that thefunc
will be the employee vector. However the relocation has to be with a size greater than 1 in 1, and still lack to store the element in the correct position.– Isac
Yeah, that’s right, that’s right.
– Lucas Correia
But the question as it is asked is not clear because it gives the idea that it intends to allocate loose users without being associated with any data structure, either list or vector. If the goal is to allocate users to a vector and increase with
realloc
can readjust the question I’ll answer it myself– Isac
Ah, yes. That’s what it was. I just forgot about that detail. Really, I want to allocate users to a vector and go up with realloc.
– Lucas Correia