Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Modify pointer value in procedure void in C

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading