【问题标题】:pass value by reference doesn't work after 2nd pass in c通过引用传递值在第二次传入 c 后不起作用
【发布时间】:2017-01-24 06:44:15
【问题描述】:
   int main()
   {
      int *x = 100;

      display(&x);

   }

   display(int *m)
   {
      show(&m);
   }

   show(int *m)
   {
      printf("%d",*m)`; 
   }

输出应该是 100。但它没有显示

【问题讨论】:

  • 你的编译器肯定在告诉你一些事情......
  • 从任何地方删除 & 符号。 int * 是地址,不需要&
  • C 不支持 pass-by-reference,它是严格的 pass-by-value!指针是一流的对象。
  • 猜猜看:&m 不是int * 类型。
  • int *x = 100;你确定你知道指针是什么/做什么?

标签: c


【解决方案1】:

你把类型弄乱了。见下文:

   int main()
   {
      int *x = 100;   // x is a "pointer to int" (with bad assignment)

      display(&x);    // Since you use &x you are passing a "pointer to a pointer to int"

   }

   display(int *m)    // but the function just expects a "pointer to int"
   {
      show(&m);       // Here you do the same
                      // m is a "pointer to int"
                      // so &m is a "pointer to pointer to int"
   }

   show(int *m)       // but the function just expects a "pointer to int"
   {
      printf("%d",*m)`; 
   }

要修复它,请执行以下操作:

   int main()
   {
      int x = 100;   // x is a "int"  (i.e. no *)

      display(&x);    // Passing a "pointer to int"

   }

   display(int *m)  
   {
      show(m);       // Just pass a "pointer to int" (i.e. no &) as 
                     // m is already "pointer to int"
   }

   show(int *m)
   {
      printf("%d",*m)`; 
   }

【讨论】:

    【解决方案2】:
    • int *x = 100; 表示“x 是引用地址 100 处的内存单元的变量”。在您的代码中手动分配指针地址几乎没有意义,因为...您为什么还要这样做?如果您稍后尝试在代码中修改变量值,您很可能会遇到运行时错误。您最好将 x 设为纯整数而不是指针。
    • &x 是变量 x 的地址。使用int *x,当调用display(&x) 时,调用签名为display(int** m) 的函数。这不是您当前的display 函数。如果您希望类型匹配,请致电 display(x)。如果您决定将x 设为纯整数,则可以保留display(&x) 调用。
    • 同上,如果你想调用show(&m),而mint*(正如你的display 签名所指定的那样),那么你的show 签名应该是show(int** m)。只需致电show(m)
    • 您的两个函数的签名中缺少返回类型。它可以使用某些编译器进行编译,但我不确定 C 规范是否允许这样做。
    • 如果要将主体放在 main 函数之后,请确保前向声明了两个函数。
    • 即便如此,函数调用中的类型不匹配也不应该编译。

    不错的尝试,但您应该更多地记录自己,那里有大量关于基本指针用法的示例!

    【讨论】:

      【解决方案3】:

      在显示函数中,已经有一个指针作为输入,不需要再取地址。您可以将指针传递给show 函数。

      display(int *m)
      {
         show(m);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-04-01
        • 2012-02-10
        • 2015-10-15
        • 1970-01-01
        • 2017-12-20
        • 2014-07-05
        相关资源
        最近更新 更多