我正在刷新我对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 = 102
,ptr = &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/