Is it passing by pointer?

旧巷老猫 提交于 2019-12-06 03:22:25

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.

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;
}

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.

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 &
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!