参数传入C指针,地址,别名 [英] Parameter Passing in C - Pointers, Addresses, Aliases
问题描述
请有人能解释一下 C 中参数传递的区别吗?
据教授指出,有4种不同的方法可以传递参数:
$ b
- 按值调用
- 呼叫地址(指针)
- 呼叫别名
- 全局变量/静态变量
如果您可以请举一个例子,我将不胜感激,并且您的工作将受到表彰。
-
按价值调用
将值作为参数传递给函数。
void fun1(int myParam)
如果函数修改变量,实际变量不会被改变。 {
myParam = 4;
}
void main()
{
int myValue = 2;
fun1(myValue);
printf(myValue =%d,myValue);
}
myValue
will always -
呼叫别名
根据我的理解,C中没有别名。它应该是C ++的引用机制。
$ li $全局变量/静态变量
全局变量和静态变量是存储在公共场所的变量,可由调用者和被调用者函数访问。因此,调用方和被调用方都可以访问和修改它们。int myValue = 2;
void fun1()
{
myValue = 4;
void main()
{
myValue = 2
fun1();
printf(myValue =%d,myValue);
code
$ b正如你所猜测的,
myValue
将会在main()
的结尾处为4个。
<$> p $ p>
void fun1(int * myParam)
{
* myParam = 4;
}
void main()
{
int myValue = 2;
fun1(& myValue);
printf(myValue =%d,myValue);
$ / code $ / pre
在这里我们传递 myValue code>到 fun1
。因此, myValue
的值在 main()
结尾处为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
- Call-by-value
- Call-by-address (pointer)
- Call-by-alias
- Global variable / Static variable
If you could please give an example, I would greatly appreciate that, and your work would be commended.
Call-by-value
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
will always be 2.Call-by-address (pointer)
void fun1(int *myParam) { *myParam = 4; } void main() { int myValue = 2; fun1(&myValue); printf("myValue = %d",myValue); }
Here we are passing the address of
myValue
tofun1
. So the value ofmyValue
will be 4 at the end ofmain()
.Call-by-alias
There is no alias in C as per my understanding. It should be the C++ reference mechanism.
Global variable / Static variable
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); }
As you can guess, the value of
myValue
will be 4 at the end ofmain()
.
Hope it helps.
这篇关于参数传入C指针,地址,别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!