【问题标题】:function that returns a pointer返回指针的函数
【发布时间】:2018-08-19 13:22:55
【问题描述】:

我正在刷新我对 C 的记忆,我想测试指针。

我做了这个简单的程序,我在其中调用了一个函数,该函数返回指向其参数中最大整数的指针

int*function_pointer (int a, int b, int c);

int main ()
{
      printf("Testing pointers\n");// line 1

      int*pointer = pointer_function(10,12,36);
      //pointer_function(10,102,36) is assigned to int*pointer

      printf("Okay, what now...\n");//line 3


      return 0;
}

指针函数

int*function_pointer (int a, int b, int c)
{
     int x;
     int*ptr = &x;
     //initially ptr points to the address of x

     if(a > b)
     {
          if(a > c)
          {
               printf("a is the greatest\n);
               ptr = &a;
          }
     }

     if(b > a)
     {
          if(b > c)
          {
              printf("b is the greatest\n");
              ptr = &b;
              //b is 102, so in this scope ptr points to the address of b
          }
     }

     if(c > a)
     {
          if(c > b)
          {
              printf("c is the greatest\n");
              ptr = &c;
          }
      }

      return ptr;
      //function returns the value of ptr which is the address of b
}
  • 在主函数function_pointer(10,102,36)被调用
  • function_pointer(...)int a, b, c 内为该范围创建
  • 最初ptr = &x
  • b = 102ptr = &b
  • 函数返回 ptr 的值
  • 在主要pointer = ptr,因此pointer = &b
  • b 超出范围,没有任何内容
  • 那么 *pointer = 102 怎么会返回垃圾值,因为 b 不在主函数的范围内

【问题讨论】:

标签: c function pointers scope


【解决方案1】:

但是 b 超出范围,并且没有任何内容

您的指针在技术上仍然有效,它只是指向内存区域。它是你的情况,当function_pointer() 返回时b 仍然指向它用于局部变量的内存(所以,在这种情况下,在你的堆栈上)。您不应该不再使用内存,但是由于 您的指针指向的内存内容默认情况下不再使用时不会归零,那么您很幸运仍然拥有以前的内存值 102 仍然存在,因为您的堆栈没有扩展超过自 function_pointer() 返回以来,不需要其他代码来执行此操作。

如果你想做一些测试,你可能想创建另一个在function_pointer() 之后调用的函数。如果该新函数需要局部变量(即 150 个 ints 的数组)。使您的代码使用更多堆栈并覆盖剩余部分。然后你将不再看到102

【讨论】:

    猜你喜欢
    • 2013-04-10
    • 1970-01-01
    • 2018-11-11
    • 2011-12-06
    • 1970-01-01
    • 2018-03-07
    • 1970-01-01
    • 2020-04-29
    相关资源
    最近更新 更多