问题
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
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);
}
回答1:
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;
}
And call it like this:
swap(&a, &f);
Note that there's no pass-by-reference in C, that's a C++ feature. In C everything, including pointers, are passed by value.
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.
来源:https://stackoverflow.com/questions/36838817/update-actual-values-using-pass-by-value