C pointers, error calling the relocation function

Asked

Viewed 103 times

0

I have the C code written below, whenever I want to invoke the function of an error that says: --/home/Amuel-o-cara/Documents/Data Structures and Algorithm/Class 13.04.16 Alocarmemoria/main. c|80|error: Conflicting types for alocarEspaco'|

pessoa* alocarEspaco(pessoa *p, int tam)
{
   pessoa* ptr = &p;
   ptr = (pessoa*) malloc(tam*sizeof(pessoa));
   return ptr;
}

3 answers

1


Conflicting types for ːalocarEspaco'

You have a function prototype (defined before, probably in a #include) signature other than the one used in the definition.

0

Your parameter is already a pointer, in which case you don’t need the "&". Also, if the function will return a pointer to the allocated space, you do not need to provide a pointer as parameter. Try as follows:

pessoa* alocarEspaco(int tam)
{
    pessoa *ptr = (pessoa*) malloc(tam*sizeof(pessoa));
    return ptr;
}

0

In his statement:

pessoa* alocarEspaco(pessoa p, int tam)

It’s not necessary pessoa p because the method will already allocate do the memory allocation. And when using size to count or allocate memory, choose to use unsigned in the description as the unsigned makes all the values you place become positive (It is more a form of organization). Thus leaving your method as follows:

pessoa* alocarEspaco(unsigned int tam)

In order to be able to allocate memory in a variable, it needs to be a pointer, and for that, it needs to * (asterisk) in the declaration.

pessoa *ptr; // essa variável é um ponteiro por que tem um "*" na declaração
ptr = (pessoa *) malloc(sizeof(pessoa)*tam);
return ptr;

Now, the variable that will receive the value, must be a pointer as well.

pessoa *var = alocarEspaco(10); // aloca 10 pessoas em var

And now the part where a lot of people get confused.

How to pick up the pointer positions?

When the pointer has 1 space is used ->. Ex:

pessoa *uma_pessoa = alocarEspaco(1);
uma_pessoa->idade = 10;
uma_pessoa->nome = "Fulano";

But of course this is for when the pointer has just 1 space. When multiple spaces are used . (point). Ex:

pessoa *muitas_pessoas = alocarEspaco(10);
muitas_pessoas[0].nome = "Ciclano";
muitas_pessoas[1].nome = "Dertrano";
/*...*/

Because that?

Because when you take a position using [n], you are already accessing the memory address. So if your pointer has a position you can use the ->, and if you have positions, you should use the [n] (number in the cushions).

  • Thanks my brothers, I investigated a little more and already solved. I only had to declare the function in the prototypes

Browser other questions tagged

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