【发布时间】: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 = 102,ptr = &b - 函数返回 ptr 的值
- 在主要
pointer = ptr,因此pointer = &b - 但
b超出范围,没有任何内容 - 那么
*pointer = 102怎么会返回垃圾值,因为 b 不在主函数的范围内
【问题讨论】: