views:

271

answers:

6
func()
{
    Object* pNext;
    func1(pNext);
}

func1(Object* pNext)
{
    pNext = Segement->GetFirstPara(0);
}

I was expecting it to be pointer to firstpara returned from func1() but I'm seeing NULL can some explain and how to fix it to actually return the firstpara() pointer?

A: 

What language?

Paul Nathan
+4  A: 

To change a pointer, you need to pass a pointer to the pointer, ie Object** pNext. To change the value of a variable inside a function, you pass a pointer. Hence, by extension, to change the value of a pointer inside a function, pass a pointer to the pointer.

func() { 
    Object* pNext;
    func1(&pNext);
}

func1(Object** pNext) { *pNext = Segement->GetFirstPara(0); }
Matthew Scharley
Dima
Matthew Scharley
A: 
Dima
+5  A: 

In c, you would want:

... func1(&pNext); ... func1(Object** pNext) { *pNext = ... }

In C++ ... func1(pNext); ... func1(Object*& pNext) { pNext = ... }

In either language, your example would pass an uninitialized Object* to func1, which would copy it, assign a value to the copy and then return. Note that the original pNext never gets modified (it would help if you used different names for your variables).

In both languages you need to explicitly pass references if pass-by-reference rather than pass-by-value is desired.

ejgottl
+15  A: 

For C++ only, you can make the parameter a reference

func()
{
    Object* pNext;
    func1(pNext);
}

func1(Object*& pNext)
{
    pNext = Segement->GetFirstPara(0);
}

What is going on here is the difference between passing parameters by value and passing by reference. C always passes by value. In order to get a value back, the value needs to be a reference value (e.g. Object** refers to Object* as a pointer). C++ adds reference parameters (signified by the &). Pass by value only passes a copy of the data and never the actual data itself. That is why the variable used in the function call was not updated in the function.

Diastrophism
+1  A: 

Please initialize pNext when you instantiate it. It might be NULL now when you're debugging, but in the field it will be 0x12AbD468, or something. The if you have a test like:

if( NULL != pNext )
{
  pNext->DoSomething();
}

...and your program will explode, users will get mad, call support and somehow get your phone extension, call you directly and give you an earful.

In your case, since 'func1()' doesnt use pNext as an in-parameter, you can simply return it from the function:

func()
{
  Object *pNext = func1();
}

Object* func1()
{
  return Segment->GetFirstPara(0);
}
John Dibling