Terry Li
Terry Li

Reputation: 17268

Is it passing by pointer?

void func(char* buf) { buf++;}

Should I call it passing by pointer or just passing by value(with the value being pointer type)? Would the original pointer passed in be altered in this case?

Upvotes: 3

Views: 176

Answers (4)

parapura rajkumar
parapura rajkumar

Reputation: 24403

This is passing by value.

void func( char * b )
{
    b = new char[4];
}

int main()
{
    char* buf = 0;
    func( buf );
    delete buf;
    return 0;
}

buf will still be 0 after the call to func and the newed memory will leak.

When you pass a pointer by value you can alter what the pointer points to not the pointer itself.

The right way to do the above stuff would be

ALTERNATIVE 1

void func( char *& b )
{
    b = new char[4];
}

int main()
{
    char* buf = 0;
    func( buf );
    delete buf;
    return 0;
}

Notice the pointer is passed by reference and not value.

ALTERNATIVE 2

Another alternative is to pass a pointer to a pointer like

void func( char ** b )
{
    *b = new char[4];
}

int main()
{
    char* buf = 0;
    func( &buf );
    delete buf;
    return 0;
}

Please note I am not in any way advocating the use of naked pointers and manual memory management like above but merely illustrating passing pointer. The C++ way would be to use a std::string or std::vector<char> instead.

Upvotes: 5

Kerrek SB
Kerrek SB

Reputation: 477040

To implement reference semantics via "passing a pointer", two things must happen: The caller must take the "address-of" the thing to be passed, and the callee must dereference a pointer.

Parts of this can be obscured by the use of arrays, which decay to a pointer to the first element - in that sense, the array content is always "passed by reference". You can use an "array-of-one" to obscure the dereferencing, though.

This is the straight-forward apporoach:

void increment_me(int * n) { ++*n; }    // note the dereference

int main() { int n; increment_me(&n); } // note the address-of

Here's the same in disguise:

void increment_me(int n[]) { ++n[0]; }     // no visible *  
int main() { int n[1]; increment_me(n); }  // or &

Upvotes: 0

Remy Lebeau
Remy Lebeau

Reputation: 596216

The pointer itself is being passed by value (the memory being pointed at is being passed by pointer). Changing the parameter inside the function will not affect the pointer that was passed in.

Upvotes: 0

Michael Dorgan
Michael Dorgan

Reputation: 12515

The pointer will not be altered. Pass by pointer means pass an address. If you want the pointer altered, you have to pass a double pointer a deference it once.


foo( char **b)
{
  *b = NULL;
}

Upvotes: 0

Related Questions