Return value of fgets into main function

北慕城南 提交于 2021-01-28 05:21:12

问题


Function fWord asks my input, and should return the first word it encounters (until the first space). It works on Online Visual Studio, but if I try to compile it with codeBlocks, my input doesn't get printed.

#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;
}

回答1:


The buffer

char buffer[20];

has local storage. It is allocated in the stack and it is released as soon as fWord returns.

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 ()).

Furthermore, as correctly noticed by @lurker in comments section, the call

fgets(input, sizeof(input), stdin);

tells fgets() to read at most sizeof(input) characters. But it will actually be the size of a char * pointer, either 4 or 8 according to your architecture.

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;
}


来源:https://stackoverflow.com/questions/61622115/return-value-of-fgets-into-main-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!