2

I was trying to write a pop function which pops a node from a linked list by using a pointer to the head pointer of the linked list

My code was:

struct stack{
  char name;
  int  info;
  struct stack *next;
};
typedef struct stack s;

The first POP Function which i wrote was (this is my first time using pointer to pointer)

1) s *pop(s **ps){
     s **temp1;
     *temp1=NULL;
     *temp1=*ps;
     *ps=(*ps)->next;
    return *temp1;
}

rather this worked

2)    s *pop(s **ps){
        s *temp2=NULL;
          temp2=*ps;
          *ps=(*ps)->next;
          return temp2;
    }

I am getting a segmentation fault for 1,whats going wrong?,Is there a better way to do this?

I used the pointer to pointer method cos i have read pointers are passed by value so even if i change something in pop using temp variable the local change wont affect the actual one

2
  • 1
    Are you missing typedef struct stack s; from the code? If not, what is the type s? Such abbreviated type names are seldom appropriate. Commented Oct 11, 2014 at 19:54
  • @JonathanLeffler Sorry i forgot to add typedef struct stack s; i will edit thanks for telling Commented Oct 12, 2014 at 4:49

2 Answers 2

3

To simplify the issue, let's illustrate using integers and pointers to integers instead of pointers and pointers to pointers:

First fragment:

int pop(int *ps){
     int *temp1;
     *temp1=0;
     *temp1=*ps;
     *ps=*ps + 1;
    return *temp1;
}

Second fragment:

int pop(int *ps){
     int temp1;
     temp1=0;
     temp1=*ps;
     *ps=*ps + 1;
    return temp1;
}

In your first code fragment, you are dereferencing an uninitialised pointer. When you try to access *temp1, you will receive an access violation because temp1 is uninitialised and probably points to NULL or some other invalid pointer. In the second fragment, we are not dereferencing it, only assigning to the memory location the compiler assigned to temp1.

The reason ps is a pointer to a pointer (or a pointer to an integer in our illustration) is because we want to change its value outside the function. Whoever calls the pop function will tell us at what location pop should write the new value. We do not have direct access to that variable so the caller needs to pass a pointer to it. Within the pop function, however, we don't need to use pointers to pointers because our local variable is accessible.

Sign up to request clarification or add additional context in comments.

Comments

3

In this here:

 s **temp1;
 *temp1=NULL;

temp1 points nowhere since it is not initialized, but you write NULL to where it points.

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.