How to allocate space for each structure of an array as the user wishes?

Asked

Viewed 69 times

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.

  • 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.

  • 1

    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 the func 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.

  • Yeah, that’s right, that’s right.

  • 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

  • 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.

Show 1 more comment

1 answer

1


To modify the size of the vector according to what the user wants to use realloc as it is already using, but it has to increase in size with each relocation, which it is not doing.

The most natural, and just as the documentation shows is to start the vector with NULL avoiding having to use malloc in the first case and even test if it is the first case. This causes no problem as the realloc behaves like a malloc if the old vector is NULL.

Citing the documentation:

In case that ptr is a null Pointer, the Function behaves like malloc, assigning a new block of size bytes and returning a Pointer to its Beginning.

In free translation

In the case of ptr be a null pointer the function behaves like a malloc, assigning a new block of size bytes and returning a pointer to its start.

In your code applying these ideas would have:

int main(int argc, char *argv[]) {
    int numEstruturas = 0, opcao = 0;
    Funcionarios *func = NULL; //vetor agora iniciado com NULL e fora do loop

    do {
        printf("Deseja adicionar outra estrutura: (1) ou (2)-sair");
        scanf("%d", &opcao);

        if(opcao == 1) {
            //realoca, passando o vetor antigo e o novo tamanho
            func = realloc(func, ++numEstruturas * sizeof(Funcionarios));

            //teste se falhou a realocação agora movido para aqui
            if(!func) { 
                printf("\nNao foi possivel alocar espaco para esta estrutura!\n");
                exit(0);
            }
        }
    } while(opcao == 1 && numEstruturas < MAX_FUNCIONARIOS);

    return 0;
}

The most important instruction since code is realloc and see how different you are from what you had, that you even lacked a parameter:

func = realloc(func, ++numEstruturas * sizeof(Funcionarios));
//              ^        ^-- numero de estruturas já aumentado para ser mais 1
//              |-- vetor antigo

I also removed the else { break; } because if the user chooses another value than the 1 the very condition of while will soon be over.

  • This will help me a lot in the test I will do tomorrow. Thank you very much, Isac.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.