通过地址,但它在C工作,如呼叫按值? [英] Passing address, but it is working like call by value in C?

查看:138
本文介绍了通过地址,但它在C工作,如呼叫按值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我的C语言编程初学者。最近我读到关于呼叫按值和呼叫按地址。我已经了解到,呼叫由被调用函数地址更改反映被调用者。而下面的code不起作用这样的。

Hello I am a beginner in C programming language. Recently I read about call by value and call by address. I have learned that in call by address changes in the called functions reflects the callee. However the following code does not work like that.

int x = 10,y = 20;
void change_by_add(int *ptr) {
    ptr = &y;
    printf("\n Inside change_by_add\t %d",*ptr);
    // here *ptr is printing 20
}

void main(){
    int *p;
    p = &x;
    change_by_add(p);
    printf("\nInside main\t %d", *p);
    // here *p is still pointing to address of x and printing 10
}

当我传递地址,然后按为何调用的函数所做的更改不会反映访问者?

When I am passing address then why the changes made by called function does not reflect caller?

推荐答案

该函数分配一个新的地址指针,但本身是由值传递的指针,因为所有的参数都在C.要改变的值指针变量的指针本身必须通过地址:

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

请参阅Ç常见问题解答问题4.8

通过引用传递中不存在C,但可以通过使可变的谁的值被改变为一个函数的地址来实现。例如:

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

这篇关于通过地址,但它在C工作,如呼叫按值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆