- 论坛徽章:
- 1
|
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
static int get_string(char *p, int size, FILE *f);
int main(int argc, char **argv)
{
FILE *fp;
int size=50;
char *p;
fp = fopen(argv[1], "r");
if(!fp) {
perror("fopen");
exit(1);
}
get_string(p, size, fp);
printf("%s\n", p);
return 0;
}
static int get_string(char *p, int size, FILE *f)
{
int c;
while( (c = getc(f)) != EOF && c != '\n') {
if(--size > 0)
*p++ = c;
else
break;
}
*p = '\0';
return 0;
}
很疑惑这段代码为什么能输出正确的结果?
char *p;
这句之后p指向哪里呢?应该是很随机的地方吧?也许是垃圾?
*p++ = c;
这句对没有初始化的指针赋值,是不是会覆盖某些其他程序的数据?
正确的写法是怎么样的?
[ 本帖最后由 FinalBSD 于 2008-12-24 13:07 编辑 ] |
|