本文共 609 字,大约阅读时间需要 2 分钟。
实验目的:
进一步理解野指针。
实验步骤:
1.分析下面的程序(例9-9)。
#include <stdio.h>
int *test( )
{
int i = 5, *pi = &i;
return pi;
}
void test2( )
{
int j = 3;
}
void main( )
{
int *pj;
pj = test( );
test2( );
printf("%d\n", *pj);
}
分析:
程序的输出结果为3,不是5,为什么?
2.比较下面两个程序。
2.1
#include <stdio.h>
void test(int *pi)
{
*pi= 5;
}
void main( )
{
int*p;
test(p);
printf("程序中其它功能……\n");
}
2.2
#include <stdio.h>
void test(int *pi)
{
if(pi== NULL)
{
printf("错误!实参为空指针!\n");
return;
}
*pi= 5;
}
void main( )
{
int*p = NULL;
test(p);
printf("程序中其它功能……\n");
}
分析:
1)两个程序中有语法错误吗?
2)两个程序运行结果相同吗?为什么?
注意:
在函数中检测指针参数是否为空指针会提高代码的健壮性。负责的程序员必须保证指针变量指向合法的地址。转载地址:http://lddti.baihongyu.com/