0

I'm trying to build a function that realloc a struct pointer (which works as an arrays of structs), but it is not working out:

I guess I'm not using the pointer reference correctly int the function cria_ponto, but I can't find out why.

TKS.

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

typedef struct ponto{
    float x, y;
} ponto;

ponto inicializa_vazio();
void cria_ponto(ponto *p, int *qntd);

int main(){
 
     int qntd_pontos = 0;
     ponto *p = NULL;
 
     cria_ponto(p, &qntd_pontos);
     printf("Coordenada x: %.2f, coordenada y: %.2f", p[0].x, p[0].y);
 
     return 0;
 
 }

 
 ponto inicializa_vazio(){
 
     ponto p;
     printf("Informe a coordenada X do ponto: ");
     scanf("%f", &p.x);
     printf("Informe a coordenada Y do ponto: ");
     scanf("%f", &p.y);
 
     return p;
};
 
 void cria_ponto(ponto *p, int *qntd){
        p = (ponto*) realloc(p, (*qntd+1)*sizeof(ponto));
        p[*qntd] = inicializa_vazio();
        *qntd = *qntd + 1;
};

  • 3
    OT: Write code in English. Sooner or later you will have to share it with others that don't understand your language, e.g. share it on SO – Support Ukraine Sep 14 '22 at 05:43
  • 1
    `p = (ponto*) realloc(p, (*qntd+1)*sizeof(ponto));` ultimately means *nothing* to the call point of `cria_ponto` in `main`. All it does is allocate memory, store the address in what amounts to a local variable, then exit the function, leaking that memory and leaving the same original `p` value back in the caller. A **debugger** and stepping through the code will reveal this. Examine the value of `p` after the function call back in `main`, but before the `printf` call. You'll see it is still NULL. – WhozCraig Sep 14 '22 at 05:43
  • `cria_ponto` can only change the local value of `p`. It can't change the value of `p` in `main`. Either pass a double pointer or return the new value of `p` – Support Ukraine Sep 14 '22 at 05:45
  • In other words: `void cria_ponto(ponto *p, int *qntd){` -> `void cria_ponto(ponto **p, int *qntd){` and update the function accordingly – Support Ukraine Sep 14 '22 at 05:47
  • 1
    Note that `realloc` receives a pointer *and returns a pointer*. Do you know why it is the case? Would `realloc` work if it just received a pointer and returned nothing? – n. m. could be an AI Sep 14 '22 at 05:58

0 Answers0