J Doe.
J Doe.

Reputation: 349

Passing pointer arguments to a double pointer argument

I have a sequence of calls where the final call requires a double pointer. It seems that I am always getting a null pointer in the end. I have simplified this down a lot to the following. The final call is a library call that returns a pointer.

This is the simplified mess. The foo in MainCaller is always 0 even though I know (through the libraries testing methods) that the object does exist.

void MainCaller(){
    foo_t *foo;
    MiddleProcessor(foo);
    // foo results as 0
}

void MiddleProcessor(foo_t *foo){
  if(1){
    ProcessorA(foo);
  }else{
    ProcessorB(foo);
  }
}

void ProcessorA(foo_t *foo){
    FinalCall(&foo);
}

void FinalCall(foo_t **foo){
    *foo = some_lib_call();
    lib_call_test_is_good_foo(foo); // true :)
}

Upvotes: 0

Views: 59

Answers (3)

Mark Ransom
Mark Ransom

Reputation: 308158

In order to modify a parameter you need to pass by reference, which you can do with an explicit reference or a pointer. If the thing you want to change is a pointer, you need a reference to a pointer or a pointer to a pointer.

Upvotes: 0

quamrana
quamrana

Reputation: 39354

The problems are that you are passing the pointer by value and FinalCall never knows where the original lives.

These changes may help:

void MainCaller(){
    foo_t *foo;
    MiddleProcessor(&foo); // Passing the address of foo means foo can be overwritten
    // foo results as 0
}

void MiddleProcessor(foo_t **foo){
  if(1){
    ProcessorA(foo);
  }else{
    ProcessorB(foo);
  }
}

void ProcessorA(foo_t **foo){
    FinalCall(foo);
}

void FinalCall(foo_t **foo){
    *foo = some_lib_call();
    lib_call_test_is_good_foo(foo); // true :)
}

Upvotes: 3

john
john

Reputation: 87959

Changing foo in FinalCall has no effect on foo in MainCaller. They're different variables why should changing one change the other?

Instead you want something like this

void MainCaller(){
    foo_t *foo;
    foo = MiddleProcessor();
}

foo_t* MiddleProcessor(){
  if(1){
    return ProcessorA();
  }else{
    return ProcessorB();
  }
}

foo_t* ProcessorA(){
    foo_t* foo;
    FinalCall(&foo);
    return foo;
}

void FinalCall(foo_t **foo){
    *foo = some_lib_call();
    lib_call_test_is_good_foo(foo); // true :)
}

Upvotes: 2

Related Questions