Home > Blockchain >  Modify pointer value in procedure void in C
Modify pointer value in procedure void in C

Time:09-26

I am trying to sort three pointers in ascending order of their value y, I'm new using pointers and pointers to pointers so i can´t see the error that is causing a segmentation fault in the execution

void sortpoints(coor **hptr, coor **mptr, coor **lptr)
{
    coor **aux;
    printf("c1 %f c2 %f c3 %f", (*hptr)->y, (*mptr)->y,(*lptr)->y);

    if ((*hptr) -> y < (*mptr) -> y)
    {
        *aux = *hptr;
        *hptr = *mptr;
        *mptr = *aux;
    }

    if ((*mptr) -> y < (*lptr) -> y)
    {
        *aux = *mptr;
        *mptr = *lptr;
        *lptr = *aux;
    }

    if ((*hptr) -> y < (*mptr) -> y)
    {
        *aux = *hptr;
        *hptr = *mptr;
        *mptr = *aux;
    }
}

This is the call, these are the first lines of the main so I'm sure the error isn't because of the rest

coor *hptr, *mptr, *lptr;
hptr = &(tptr -> p1);
mptr = &(tptr -> p2);
lptr = &(tptr -> p3);
sortpoints(&hptr, &mptr, &lptr);
printf("c1 %f c2 %f c3 %f", hptr->y, mptr->y,lptr->y);

An expected execution should be like

c1 10 c2 1 c3 400
c1 400 c2 10 c3 1 

CodePudding user response:

You declared an uninitialized pointer

coor **aux;

So dereferencing it like

*aux = *hptr;

invokes undefined behavior.

You need to declare the pointer like

coor *aux;

and assign a value to it like

aux = *hptr;
  • Related