Members of a structure as pointers

Asked

Viewed 47 times

-2

In the code below I am trying to define a structure whose members are pointers that will be used to work with the name, email and age data, all dynamically allocated, of an employee. However, the programme closes when qtdeFuncionarios > 1.

#include <stdio.h>
#include <stdlib.h>
#include<string.h>

struct funcionario{
    char *nome;
    char *email;
    int *idade;
};

int main() {
    int opcao, qtdeFuncionarios, i;
    printf("1.Cadastrar funcionario\n");
    printf("2.Listar funcionarios\n");
    printf("3.Editar dados de funcionario\n");
    printf("4.Excluir funcionario\n");
    scanf("%d", &opcao);

    if(opcao = 1){
        printf("Quantos funcionarios deseja cadastrar? ");
        scanf("%d", &qtdeFuncionarios);
        struct funcionario *f = (struct funcionario *)malloc(qtdeFuncionarios * sizeof(struct funcionario));

        for(i = 0; i < qtdeFuncionarios; i++){  
            char *nome = (char *)malloc(35*sizeof(char));
            printf("Digite o nome do funcionario %d: ", i);
            scanf("%s", nome );
            strcpy(f[i].nome, nome);

            printf("%s", f[i].nome );

            char *email= (char *)malloc(35*sizeof(char));
            printf("Digite o email do funcionario %d: ", i);
            scanf("%s", email);
            strcpy(f[i].email, email);
            printf("%s", f[i].email );

            printf("Digite a idade do funcionario %d: ", i);
            scanf("%d", &f[i].idade);
            printf("%d", f[i].idade );
        }

    }

    return 0;
}
  • Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site (when you have enough score).

2 answers

1

There are several mistakes. Some not exactly mistakes, but that could be better.

I preferred to use a typedef that creates a type and makes it much easier to manipulate it.

Changed idade to have no pointer because it makes no sense and in fact the algorithm does not use as pointer, which is probably the cause of the error described in the question.

The if had a value assignment for the variable and not a comparison, only worked by coincidence, when continued would give problem.

I simplified the lease that you were doing unnecessary things that cause problems.

I eliminated the creation of unnecessary variables, and with that the unnecessary copy.

I also protected the data entry allowing only the amount of characters that fits the buffer servant.

I gave a better name to the variable. Don’t be too lazy to type the name.

I did nothing to free up the memory you allocated with malloc(), but the right thing to do is to do it at some point as appropriate. In exercise it may not be a problem, but get used to doing the right thing using the free() Even if you don’t have to, you even train the right place and see if you can put it in before it’s time or leak something.

You can improve some more points.

#include <stdio.h>
#include <stdlib.h>

typedef struct {
    char *nome;
    char *email;
    int idade;
} Funcionario;

int main() {
    int opcao, qtdeFuncionarios;
    printf("1.Cadastrar funcionario\n");
    printf("2.Listar funcionarios\n");
    printf("3.Editar dados de funcionario\n");
    printf("4.Excluir funcionario\n");
    scanf("%d", &opcao);
    if (opcao == 1) {
        printf("Quantos funcionarios deseja cadastrar? ");
        scanf("%d", &qtdeFuncionarios);
        Funcionario *funcionarios = malloc(qtdeFuncionarios * sizeof(Funcionario));
        for (int i = 0; i < qtdeFuncionarios; i++) {  
            funcionarios[i].nome = malloc(35);
            printf("\nDigite o nome do funcionario %d: ", i);
            scanf("%34s", funcionarios[i].nome);
            printf("\n%s", funcionarios[i].nome);
            funcionarios[i].email = malloc(35);
            printf("\nDigite o email do funcionario %d: ", i);
            scanf("%34s", funcionarios[i].email);
            printf("\n%s", funcionarios[i].email);
            printf("\nDigite a idade do funcionario %d: ", i);
            scanf("%d", &funcionarios[i].idade);
            printf("\n%d", funcionarios[i].idade);
        }
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • Awesome! Thank you so much for all the placements. Can you please tell me more about the relevance of this typedef?

  • https://answall.com/q/364771/101 and https://answall.com/q/397436/101 Almost everything you want to know is already here on the site.

0

Your program must be failing because you are running a series of indefinite instructions. He is allocating memory in a few moments but is not treating it correctly. His code is with several errors. Follow below my comments.

The first mistake is that the if is not comparing whether opcao is equal to 1, but is assigning the value 1 to the variable opcao. Thus the implementation of the programme at all times will execute the code within the if. The right thing would be to use the operator ==:

if (opcao == 1) {
    ...

After that you allocate memory to the employee’s name and email but instead of assigning memory to members you try to copy the data to them while they are still invalid. The correct thing would be to change the calls strlcpy() by simply assigning the pointers:

f[i].nome = nome; // ao invés de strcpy(f[i].nome, nome);
...
f[i].email = email; // ao invés de strcpy(f[i].email, email);

In the case of age I do not recommend using pointer to dynamically allocated memory, since integers have fixed size (4 bytes or 8 bytes usually). I recommend changing member type idade of int * simply to int. That way the age reading would look like this:

struct funcionario{
    char *nome;
    char *email;
    int idade;
};
...
...
    printf("Digite a idade do funcionario %d: ", i);
    scanf("%d", &f[i].idade);
    printf("%d\n", f[i].idade );

At last you should worry about dislocating all that acquired memory. If your program does not do this memory leaks will occur (or memory Leaks) and in extensive applications (which is not the case for your example) this can be a serious problem.

Browser other questions tagged

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