1

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 
1
  • Side note: Doing (e.g.) x -> y is not as standard/idiomatic as x->y (without the spaces). Commented Sep 25, 2022 at 18:13

1 Answer 1

0

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.