update actual values using pass by value

你。 提交于 2019-12-12 03:28:38

问题


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

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