错误代码:
line是在函数中声明的一个变量,函数执行完后便不复存在,此函数传回的只是line的地址,不能得到字符。要得到字符,应该像C库中的fgets()函数那样写(在<C程序设计语言(第二版)>(中文)(Brian W.Kernighan&Dennis M.Ritchie>书第145页),把line在函数外定义好,把其地址作为形参传入函数,再对其赋值。
还应注意一点,fgets的第一个参数只能接收字符数组作为参数,不能是char *类型的。
测试代码:
运行结果:
见代码注释。
/*
get the NUMth line of a file
*/
char * getN( FILE * iop, int n)
{
char line[ 300 ];
rewind(iop);
int i;
for ( i = 1 ; i <= n ; i ++ )
fgets(line, 1000 , iop);
return line;
}
char * getN( FILE * iop, int n)
{
char line[ 300 ];
rewind(iop);
int i;
for ( i = 1 ; i <= n ; i ++ )
fgets(line, 1000 , iop);
return line;
}
还应注意一点,fgets的第一个参数只能接收字符数组作为参数,不能是char *类型的。
测试代码:
#include
<
stdio.h
>
main()
{
char * s = " he:jun " ;
char * f[ 20 ];
char * x;
f[ 0 ] = s; // it's address copy,not var copy
x = s; // it's address copy,not var copy
s = " news " ; // set var(s)like this , var(s) will be alloc a new memory space ,and s get a new address
printf( " s=%s f[0]=%s x=%s " ,s,f[ 0 ],x);
printf( " sADDR%d xADDR%d f[0]ADDR%d " ,s,x,f[ 0 ]);
}
main()
{
char * s = " he:jun " ;
char * f[ 20 ];
char * x;
f[ 0 ] = s; // it's address copy,not var copy
x = s; // it's address copy,not var copy
s = " news " ; // set var(s)like this , var(s) will be alloc a new memory space ,and s get a new address
printf( " s=%s f[0]=%s x=%s " ,s,f[ 0 ],x);
printf( " sADDR%d xADDR%d f[0]ADDR%d " ,s,x,f[ 0 ]);
}
运行结果:
见代码注释。