Passing address, but it is working like call by value in C?

青春壹個敷衍的年華 提交于 2019-11-27 15:54:00

The function is assigning a new address to the pointer but the pointer itself is being passed by value, as all arguments are in C. To change the value of a pointer variable the address of the pointer itself must be passed:

void change_by_add(int **ptr)
{
    *ptr = &y;
}

change_by_add(&p);

See C FAQ Question 4.8.

Passing by reference does not exist in C but can be achieved by passing the address of the variable who's value is to be changed to a function. For example:

void add_to_int(int* a_value, int a_increment)
{
    *a_value += a_increment;
}

You are simply setting the value of the pointer in the function, not the value of the pointed to variable. The function should use the following code:

*ptr = y;

This derefences the pointer (exposing the value pointed to), and therefore when you use the equals operator, the memory pointed at is modified, not the pointer itself. I hope this helps to clarify things.

There is no such thing as call by address in C. There is only call by value. What one does when a function needs to modify an argument in a way that is visible to the caller is to have the caller pass a pointer to something, and have the called function write the update though that pointer. Note that the pointer itself is still sent as call-by-value - that is: the called function gets its own copy of the pointer and could change it to point to anything else if it wants to.

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