Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
228 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...