C pointers, error invoking the reallocation function

0

I have the C code written below, whenever I want to invoke the function of an error that says: - / home / samuel-o-face / Documents / Data Structures and Algorithm / Class 13.04.16 AllocatingMemory / main.c | 80 | error: conflicting types for 'alocarSpaco' |

pessoa* alocarEspaco(pessoa *p, int tam)
{
   pessoa* ptr = &p;
   ptr = (pessoa*) malloc(tam*sizeof(pessoa));
   return ptr;
}
    
asked by anonymous 17.04.2016 / 08:12

3 answers

1
  

conflicting types for 'alocarSpaco'

You have a prototype of the function (defined above, probably in a #include ) with a different signature than the one used in the definition.

    
17.04.2016 / 13:11
0

Your parameter is already a pointer, in which case you do not need the "&". Also, if the function returns a pointer to the allocated space, you do not need to supply a pointer as a parameter. Please try the following:

pessoa* alocarEspaco(int tam)
{
    pessoa *ptr = (pessoa*) malloc(tam*sizeof(pessoa));
    return ptr;
}
    
17.04.2016 / 08:25
0

In your statement:

pessoa* alocarEspaco(pessoa p, int tam)

% is not required because the method will already allocate memory allocation. And when using size to count or allocate memory, opt to use pessoa p in the description, because unsigned causes all values that you put to become positive (It's more a form of organization). So leaving your method as follows:

pessoa* alocarEspaco(unsigned int tam)

In order to allocate memory in a variable, it needs to be a pointer, and for that, it is necessary to place a unsigned (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 is to receive the value must be a pointer as well.

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

And now the part that a lot of people make confusing.

  

How to get pointer positions?

When the pointer has 1 space it uses * . Ex:

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

But of course this is for when the pointer has only 1 space. When you have multiple spaces, use -> (dot). Ex:

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

Why this?

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

    
17.04.2016 / 09:33