使用指针模拟“按值传递"函数(C和C ++)中的“按引用传递" [英] Using pointers to emulate Pass-by-Reference in a Pass-by-Value function (C and C++)
问题描述
因此,我试图理解一段简单的代码,该代码使用按值传递"函数中的指针来模拟"按引用传递.该示例是C惯例,因为C中没有通过引用的传递.但是我也很好奇它对C ++的影响.
So I am trying to understand a simple piece of code that 'emulates' Pass-by-reference using pointers in a Pass by value function. The example is given as a C practice since there is no Pass by reference in C. but I am also curious about its effects on C++.
因此,运行此代码后,将交换值:
so after running this code the values are swapped:
void swap(int* a, int* b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
我试图理解为什么将指针作为参数传递会产生按引用传递效果?这是否意味着通过指针执行的所有操作都具有按引用传递"效果?因此,一旦退出函数,交换的内存位置将不会返回?这在C ++中也有效吗?
I am trying to understand why passing pointers as arguments create a pass-by-reference effect? Does it mean all actions that are performed through pointers have a pass-by-reference effect? So the swapped memory location will not go back once we quit the function? Would this also be valid in C++?
编码新手,所以我希望我能说清楚.
New to coding so I hope I could make myself clear.
推荐答案
基本上,您的代码正在将内存地址复制到函数中,而如果省略了*
运算符,则函数将复制 函数的内存地址.这就是每行本质上的意思.
Basically, your code is copying a memory address to the function, while if you omitted the *
operator, the function would be copying what's in a memory address to the function. Here's what each line is essentially saying.
// Give me the memory address of a and b.
void swap(int* a, int* b)
{
int temp;
// Whatever value is at memory address 'a', copy it to temp.
temp = *a;
// Whatever value is at memory address 'b', copy it to memory address 'a'.
*a = *b;
// Copy temp over the value at memory address 'b'.
*b = temp;
}
是的,在C ++中同样有效.
And yes, it would be equally valid in C++.
这篇关于使用指针模拟“按值传递"函数(C和C ++)中的“按引用传递"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!