c - 返回指针的函数

标签 c function pointers scope

我正在刷新我对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 不在 main 函数的范围内

最佳答案

but b is out of scope, and doesn't have any content

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

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

关于c - 返回指针的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49219719/

相关文章:

swift - 如何在 Swift 中制作解码泛型函数

c++ - 这两种说法的区别? - C++

java - 如何在主java中调用Keypress函数

c++ - 传递三重指针以在另一个函数中分配内存,sscanf 异常

c++ - 如何初始化和定义指向二维数组的指针?

c - 接受返回现有连接,导致段错误

c - 访问类型的 Ada 数组

python - 如何在大小为 `n` 次 `m` (n≠m) 的非方阵的 numpy 数组上使用 c 函数进行计算

c - 简单的 "for loop"在C中没有计算出正确的数字

javascript - 显示注册表单而不是登录表单