gpt4 book ai didi

c - 使用按值传递更新实际值

转载 作者:太空宇宙 更新时间:2023-11-04 08:14:06 26 4
gpt4 key购买 nike

我想知道是否有任何方法可以使用按值传递来更新原始值。

另外我想知道我是否可以将更新后的地址返回给 main

这里我不想使用引用传递来交换 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.

是的,你需要传递一个指针:

void swap(int* a, int* b)
{
int temp = *a;
*a = *b;
*b = temp;
}

然后这样调用它:

swap(&a, &f);

请注意,C 中没有按引用传递,这是 C++ 的一个特性。在 C 中,一切,包括指针,都是按值传递的。

按值传递在 C 中意味着复制,因此不可能修改传递的内容。

Also i want to know if I can return updated address back to main

是的,你可以。只需将函数返回类型更改为指针类型,并添加带有您选择的变量地址的 return 语句。

关于c - 使用按值传递更新实际值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36838817/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com