Problem with memory allocation for the second time

Asked

Viewed 32 times

0

well, the program works correctly in the first for loop, but in the second it hangs when trying to allocate "q" for the second time. follows part of the code:

void Insere(Poligono p, double x, double y){
    Poligono q;
    q = (Poligono)malloc(sizeof(Poligono));
    printf("teste\n");
    q->x = x;
    q->y = y;
    q->prox = p->prox;
    p->prox = q;
}
int main(){
    int vertices, i;
    double x, y;
    Poligono p = Cuca();//cabeca
    printf("Vertices: ");
    scanf(" %d", &vertices);
    for(i = 0; i < vertices; i++){
        printf("Coordenadas: ");
        scanf(" %f %f", &x, &y);
        Insere(p, x, y);
    }
    ImprimeLista(p);
    return 0;
}
  • I can try, but the only difference between malloc and calloc and calloc allocates and zero "poe" in n positions ?

  • I don’t know if it’s the cause of your problem but how you declared your variables x and y as double the format specification in the scanf function should if %lf.

  • @Michel, without the full code it is difficult to say which error. What I noticed is that your malloc is wrong. I’m guessing that Poligono must be a typedef for struct poligono*. If that’s the case, malloc(Poligono) will be reserving space in memory only to store a pointer, not to store the structure struct poligono. The right thing would be q = (Poligono)malloc(sizeof(struct poligono))

  • was this msm, after a while researching discovered this, mt thank you, I will start posting the whole code of agr on, I am new here :D

1 answer

0


The variable q is not a pointer to Polygon struct. By analyzing your code you have head(cuca) but are not using pointers anywhere in the code.

In my mind it should be something like this

Poligono *p = Cuca();
void Insere(Poligono *p, double x, double y){
    Poligono *q = malloc(sizeof(Poligono));

Your prox inside the Poligono struct also has to be a pointer.

  • thanks :D, helped me mt

Browser other questions tagged

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