Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
214 views
in Technique[技术] by (71.8m points)

How to get string as return value from function in C?

I am a newbie in C and am trying to make a hangman game where a player will have to guess a random word selected by the program. But I am stuck in getting the word. I tried a lot and found some answers on SO but could not relate it to my case.

Here's the code:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

char dictionary[3][15] = {"food","cat","coder"};
//15 is max length of each word

char getWord() {
    srand(time(0));
    char *random_elem = dictionary[rand()%3];
    printf(random_elem);
    return random_elem;
}


void gamePlay() {
    *word = getWord();
    printf(*word);
    return;
}

int main() {

    printf("Welcome to Hangman
");
    printf("------------------------------------

");

    gamePlay();
}

The printf in the getWord() works but not in gamePlay()

The following error is generated:

<stdin>:11:12: warning: format string is not a string literal (potentially insecure) [-Wformat-security]
    printf(random_elem);
           ^~~~~~~~~~~
<stdin>:11:12: note: treat the string as an argument to avoid this
    printf(random_elem);
           ^
           "%s", 
<stdin>:12:12: error: cannot initialize return object of type 'char' with an lvalue of type 'char *'
    return random_elem;
           ^~~~~~~~~~~
<stdin>:17:6: error: use of undeclared identifier 'word'; did you mean 'for'?
    *word = getWord();
     ^~~~
     for
<stdin>:17:6: error: expected expression
<stdin>:18:13: error: use of undeclared identifier 'word'
    printf(*word);
            ^
1 warning and 4 errors generated.

OS: Android 11 App: Cxxdroid

If that might help


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The right code is the above.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

char dictionary[3][15] = {"food","cat","coder"};
//15 is max length of each word

char* getWord() {
    srand(time(0));
    char *random_elem = dictionary[rand()%3];
    printf("%s
",random_elem);
    return random_elem;
}


void gamePlay() {
    char *word = getWord();
    printf("%s
",word);
    return;
}

int main() {

    printf("Welcome to Hangman
");
    printf("------------------------------------

");

    gamePlay();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...