返回指针的函数

福特

我正在刷新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)被称为
  • inside function_pointer(...)int a, b, c是为该范围创建的
  • 原来 ptr = &x
  • 由于b = 102ptr = &b
  • 函数返回ptr的值
  • 在主要pointer = ptr,因此pointer = &b
  • b超出范围,并且没有任何内容
  • 那么怎么回事*pointer = 102,它不应该返回垃圾值,因为b不在主函数的范围内
马尔辛·奥尔洛夫斯基

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

从技术上讲,您的指针仍然有效,并且仅指向内存区域。根据您的情况,当function_pointer()返回b仍然指向其用于局部变量的内存时(因此,在本例中为堆栈)。不应该再使用内存,但是由于指针所指向的内存内容在不再使用时默认不为零,因此很幸运您仍然可以保留先前的值102,因为您的堆栈没有扩展自function_pointer()返回,因为不需要其他代码即可执行此操作。

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章