[英]Return value of fgets into main function
Function fWord
asks my input, and should return the first word it encounters (until the first space). Function fWord
询问我的输入,并且应该返回它遇到的第一个单词(直到第一个空格)。 It works on Online Visual Studio, but if I try to compile it with codeBlocks, my input doesn't get printed.它适用于 Online Visual Studio,但如果我尝试使用 codeBlocks 编译它,我的输入不会被打印。
#include <stdio.h>
#include <string.h>
#include <ctype.h>
char * fWord();
char * test;
int main()
{
test = fWord();
printf("%s\n", test);
return 0;
}
char * fWord() // ONLY READ THE FIRST WORD
{
char buffer[20];
char * input = buffer;
fgets(input, sizeof(input), stdin);
input = strtok(input, " ");
input[strcspn(input, "\r\n")] = 0; // REMOVES NEWLINE FROM GETLINE
return input;
}
The buffer缓冲区
char buffer[20];
has local storage.有本地存储。 It is allocated in the stack and it is released as soon as fWord
returns.它在堆栈中分配,并在fWord
返回后立即释放。
You need to allocate it externally (either as global variable or as a local variable of function main
passing it as a new parameter of fWord
) or keep allocating within fWord
but dynamically (using malloc ()
).您需要在外部分配它(作为全局变量或作为 function main
的局部变量将其作为fWord
的新参数传递)或在fWord
内动态分配(使用malloc ()
)。
Furthermore, as correctly noticed by @lurker in comments section, the call此外,正如@lurker 在评论部分正确注意到的那样,调用
fgets(input, sizeof(input), stdin);
tells fgets()
to read at most sizeof(input)
characters.告诉fgets()
最多读取sizeof(input)
字符。 But it will actually be the size of a char *
pointer, either 4 or 8 according to your architecture.但它实际上是char *
指针的大小,根据您的架构,可以是 4 或 8。
In conclusion, your program will become:总之,您的程序将变为:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAX_INPUT_LEN 20
char * fWord(void);
int main(void)
{
char *test = fWord();
if (test) //fWord might return a NULL pointer
{
printf("%s\n", test);
free(test);
}
return 0;
}
char * fWord(void) // ONLY READ THE FIRST WORD
{
char * input = malloc(MAX_INPUT_LEN);
if (input)
{
fgets(input, MAX_INPUT_LEN, stdin);
input[strcspn(input, "\r\n")] = 0; // REMOVES NEWLINE FROM GETLINE
input = strtok(input, " ");
}
return input;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.