C 中的参数传递 - 指针、地址、别名 [英] Parameter Passing in C - Pointers, Addresses, Aliases
问题描述
有人可以解释一下C中参数传递的区别吗?根据教授笔记有4种不同的参数传递方式
Could someone please explain the difference between parameter passing in C please? According to professor notes there are 4 different ways to pass parameters
- 按价值调用
- 按地址调用(指针)
- 别名调用
- 全局变量/静态变量
如果你能举个例子,我将不胜感激,你的工作也会受到赞扬.
If you could please give an example, I would greatly appreciate that, and your work would be commended.
推荐答案
价值调用
将值作为参数传递给函数.如果函数修改了变量,实际变量不会改变.
Passing the value to a function as a parameter. If the function modifies the variable, the actual variable won't get changed.
void fun1(int myParam)
{
myParam = 4;
}
void main()
{
int myValue = 2;
fun1(myValue);
printf("myValue = %d",myValue);
}
myValue
将始终为 2.
按地址调用(指针)
void fun1(int *myParam)
{
*myParam = 4;
}
void main()
{
int myValue = 2;
fun1(&myValue);
printf("myValue = %d",myValue);
}
这里我们将myValue
的地址传递给fun1
.所以 myValue
的值在 main()
的末尾将是 4.
Here we are passing the address of myValue
to fun1
. So the value of myValue
will be 4 at the end of main()
.
别名调用
根据我的理解,C 中没有别名.应该是C++引用机制.
There is no alias in C as per my understanding. It should be the C++ reference mechanism.
全局变量/静态变量
全局变量和静态变量是存储在公共位置的变量,可由调用者和被调用者函数访问.所以调用者和被调用者都可以访问和修改它们.
Global and static variables are variables stored in a common places, accessible by the caller and callee functions. So both caller and callee will be able to access and modify them.
int myValue = 2;
void fun1()
{
myValue = 4;
}
void main()
{
myValue = 2
fun1();
printf("myValue = %d",myValue);
}
如您所料,main()
末尾的 myValue
的值将是 4.
As you can guess, the value of myValue
will be 4 at the end of main()
.
希望有帮助.
这篇关于C 中的参数传递 - 指针、地址、别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!