Assigning a new adress to a pointer in a function not possible? [duplicate]

Deadly 提交于 2019-12-02 12:44:19

Memory allocating functions return the pointer value, so it is generally assigned to a pointer.

Passing a pointer to a function as an argument is a different story, because changing it won't change the original (pass by value). That's why we use pointers in these cases, to give the address of a variable and change its value in the function.

If you need to pass a pointer instead, and change what it points to, use a pointer to a pointer!

void
my_function(int **pointer)
{
    *pointer = &something;  // will change the pointer address
}

int *my_pointer = &something_else;
my_function(&my_pointer);

It's because all parameters are passed by value in C. If you call a function with a pointer parameter you may change that pointer in the function but this will have no effect on the caller's value of the pointer.

If you need to communicate a modified pointer back to the caller, returning the modified pointer is the way to go. Note that this also only passes a value back.

Another way would be to pass the address of a pointer (i.e. a pointer to a pointer). The called function can then store a new pointer value at the given address.

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