将fgets()与char *类型一起使用 [英] Using fgets() with char* type

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

问题描述

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

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.

Google想要什么

What the google wants from you, is this:

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

和a

free(temp);

在您不再需要它之后。

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

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