使用传值更新实际值 [英] update actual values using pass by value
问题描述
我想知道是否有任何方法可以通过值传递来更新原始值.
I want to know if there is any way to update original values by using pass by value.
我也想知道我是否可以将更新后的地址返回给主
Also i want to know if I can return updated address back to main
这里我不想使用引用传递来交换 main 中的原始值.
Here I dont want to use pass by reference to swap original values in main.
#include<stdio.h>
int a = 100;
int f =200;
int *p, * q;
swap(int, int);
main()
{
printf("%d %d\n", a,f);
swap(a, f);
printf("%d %d\n",a ,f); //values remain same here how to change them
}
swap(int a, int f)
{
int t;
p=&a;
q=&f;
t=*p;
*p=*q;
*q= t;
printf("%d %d\n",a ,f);
}
推荐答案
我想知道是否有任何方法可以通过值传递来更新原始值.
I want to know if there is any way to update original values by using pass by value.
是的,你需要传递一个指针:
Yes there is, you need to pass a pointer:
void swap(int* a, int* b)
{
int temp = *a;
*a = *b;
*b = temp;
}
然后这样称呼它:
swap(&a, &f);
请注意,C 中没有传递引用,这是 C++ 的特性.在 C 中一切,包括指针,都是按值传递的.
Note that there's no pass-by-reference in C, that's a C++ feature. In C everything, including pointers, are passed by value.
而传值在 C 中意味着复制,因此无法修改传递的内容.
And pass-by-value means copy in C, so it's impossible to modify what was passed.
我也想知道我是否可以将更新后的地址返回给主
Also i want to know if I can return updated address back to main
是的,你可以.只需将函数返回类型更改为指针类型并添加带有您选择的变量地址的返回语句即可.
Yes you can. Just change the function return type to a pointer type and add a return statement with the address of the variable of your choice.
这篇关于使用传值更新实际值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!