简体   繁体   中英

Return value of fgets into main function

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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