简体   繁体   English

使用带有char *类型的fgets()

[英]Using fgets() with char* type

I have a simple question about using fgets() with char* string. 我有一个关于将fgets()与char * string一起使用的简单问题。

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

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

This code didn't work well. 这段代码效果不好。

But after I modified char *temp to char temp[100]; 但是在我将char *temp修改为char temp[100]; , the code worked well as I intended. ,代码运行良好,我打算。

What is the difference between those two? 这两者有什么区别?

When I googled it, some said that memory must be allocated to char * using malloc()... 当我用Google搜索它时,有人说必须使用malloc()将内存分配给char * ...

But I couldn't understand it. 但我无法理解。

char *temp is only a pointer. char * temp只是一个指针。 At begin it doesn't points to anything, possibly it has a random value. 在开始时它不指向任何东西,可能它具有随机值。

fgets() reads 500 bytes from fp to the memory addresse, where this temp pointer points! fgets()从fp读取500个字节到内存地址,这个临时指针指向! So, it can overwrite things, it can make segmentation faults, and only with a very low chance will be work relativale normally. 因此,它可以覆盖事物,它可以使分段错误,并且只有非常低的机会才能正常工作。

But char temp[500] is a 500 bytes long array. 但char temp [500]是一个500字节长的数组。 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. 因此,这500字节将是一个可用的500字节,但它有一个价格:你不能重新分配,调整大小,免费等等。

What the google wants from you, is this: 谷歌想要你的是这样的:

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

And a 还有一个

free(temp);

after you don't need this any more. 在你不再需要它之后。

char *temp is uninitialized, that is, it isn't pointing to valid memory. char *temp未初始化,也就是说,它没有指向有效的内存。 Either make it an array ( char temp[] ) or use malloc to assign memory for it. 要么使它成为一个数组( char temp[] ),要么使用malloc为它分配内存。

When we write 当我们写作

char *temp ; 

it means temp is an uninitialized pointer to char ie currently it does not contain any address in it . 它表示temp是一个未初始化的指向char指针,即当前它不包含任何地址。

While using fgets you have to pass a string in which the bytes read from file pointer is to be copied . 在使用fgets您必须传递一个字符串,其中要复制从文件指针读取的字节。 link since the temp is uninitialized , the fgets looks like this 链接因为temp未初始化, fgets看起来像这样

fgets(<no string> , 500 , fp ) ;

which is invalid . 这是无效的。

Hence , we should give initialized string which can be formed as : 因此,我们应该给出初始化的字符串,可以形成如下:

1) char *temp = malloc(sizeof(500)) ;
or
2) char temp[500] ;

Hence if we pass initialized string to fgets , it would look like 因此,如果我们将初始化的字符串传递给fgets ,它看起来就像

fgets( < some string > , 500 , fp) ;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM