Why use a pointer to struct instead of the struct itself in this case?

Asked

Viewed 51 times

0

Why, in the struct GERENTE and CLIENTE, I have to use a pointer to the struct PESSOA and not the struct PESSOA

typedef struct{
    char* nome;
    int cpf;
} PESSOA;

typedef struct{
   PESSOA* pessoa;
   int valorContaCorrente;
   int valorDaDivida;
   char tipo;
} CLIENTE;

typedef struct{
   PESSOA* pessoa;
   int numClientes;
   CLIENTE* clientes[20];
} GERENTE;

1 answer

3


It can have many reasons, including several wrong ones. It seems to be an exercise that asks to do this. If he asks, he should explain why, if he doesn’t explain, it’s not a good exercise.

Pointer is a indirect, then the biggest reason to use a pointer is because it needs an indirect. But the specific reason I need an indirect I can’t answer because I don’t know what problem you’re trying to solve. Artificial problems are not good for learning to program.

Without the pointer the structure used will be allocated right there, what we call inplace, then into this new struct will have a space reserved for the object of the other struct. So the reason is the same one you used char * and not char[30] for example. The pointer says that you will allocate the object elsewhere and there you will only put the address of that other place. If you want it then great, if you don’t want it, you don’t have to do it like this.

Obviously as well as expected to store memory to use in nome, also at some point of the code will have to allocate memory to pessoa, and of course, then initialize the object at that location.

I can’t even say that it’s the right thing to do because all the members of these structures seem to use wrong types, maybe because the intention is just to learn to put something in C, and not to program correctly, but that’s another issue unrelated to the question itself. Training error makes one get used to it.

Browser other questions tagged

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