使用带有 char* 类型的 fgets() [英] Using fgets() with char* type

查看:17
本文介绍了使用带有 char* 类型的 fgets()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于使用 fgets() 和 char* 字符串的简单问题.

I have a simple question about using fgets() with char* string.

....
char *temp;
FILE fp=fopen("test.txt", "r");

fgets(temp, 500, fp);
printf("%s", temp);
....

这段代码运行不好.

但是在我将 char *temp 修改为 char temp[100]; 后,代码运行良好.

But after I modified char *temp to char temp[100];, the code worked well as I intended.

这两者有什么区别?

当我用谷歌搜索时,有人说必须使用 malloc() 将内存分配给 char *...

When I googled it, some said that memory must be allocated to char * using malloc()...

但我无法理解.

推荐答案

char *temp 只是一个指针.一开始它不指向任何东西,可能它有一个随机值.

char *temp is only a pointer. At begin it doesn't points to anything, possibly it has a random value.

fgets() 从 fp 读取 500 个字节到这个临时指针指向的内存地址!所以,它可以覆盖东西,它可以产生分段错误,并且只有极低的机会才能正常工作.

fgets() reads 500 bytes from fp to the memory addresse, where this temp pointer points! So, it can overwrite things, it can make segmentation faults, and only with a very low chance will be work relativale normally.

但是 char temp[500] 是一个 500 字节长的数组.这意味着,编译器在您的进程开始时(或在您的函数调用时)进行分配.因此这 500 字节将是可用的 500 字节,但它有一个代价:你不能重新分配、调整大小、释放等等.

But char temp[500] is a 500 bytes long array. That means, that the compiler does the allocation on the beginning of your process (or at the calling of your function). Thus this 500 bytes will be a useable 500 bytes, but it has a price: you can't reallocate, resize, free, etc. this.

谷歌想从你这里得到什么,是这样的:

What the google wants from you, is this:

char *temp = (char*)malloc(500);

还有一个

free(temp);

在你不再需要这个之后.

after you don't need this any more.

这篇关于使用带有 char* 类型的 fgets()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆