参数传入C指针,地址,别名 [英] Parameter Passing in C - Pointers, Addresses, Aliases

查看:99
本文介绍了参数传入C指针,地址,别名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请有人能解释一下 C 中参数传递的区别吗?
据教授指出,有4种不同的方法可以传递参数:
$ b


  1. 按值调用

  2. 呼叫地址(指针)

  3. 呼叫别名

  4. 全局变量/静态变量

如果您可以请举一个例子,我将不胜感激,并且您的工作将受到表彰。

解决方案


  1. 按价值调用

    将值作为参数传递给函数。

      void fun1(int myParam)
    如果函数修改变量,实际变量不会被改变。 {
    myParam = 4;
    }

    void main()
    {
    int myValue = 2;
    fun1(myValue);
    printf(myValue =%d,myValue);
    }

    myValue will always



  2. <$> 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。


  3. 呼叫别名



    根据我的理解,C中没有别名。它应该是C ++的引用机制。
    $ li $全局变量/静态变量

    全局变量和静态变量是存储在公共场所的变量,可由调用者和被调用者函数访问。因此,调用方和被调用方都可以访问和修改它们。

      int myValue = 2; 
    void fun1()
    {
    myValue = 4;

    void main()
    {
    myValue = 2
    fun1();
    printf(myValue =%d,myValue);

    code


    $ b

    正如你所猜测的, 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

  1. Call-by-value
  2. Call-by-address (pointer)
  3. Call-by-alias
  4. Global variable / Static variable

If you could please give an example, I would greatly appreciate that, and your work would be commended.

解决方案

  1. 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.

  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 to fun1. So the value of myValue will be 4 at the end of main().

  3. Call-by-alias

    There is no alias in C as per my understanding. It should be the C++ reference mechanism.

  4. 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 of main().

Hope it helps.

这篇关于参数传入C指针,地址,别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆