首页 > 解决方案 > 如何从C中的函数获取字符串作为返回值?

问题描述

我是 C 的新手,正在尝试制作一个刽子手游戏,玩家必须猜测程序选择的随机单词。但我被困在了这个词上。我尝试了很多,并在 SO 上找到了一些答案,但无法将其与我的案例联系起来。

这是代码:

#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\n");
    printf("------------------------------------\n\n");

    gamePlay();
}

在作品printfgetWord()但不在gamePlay()

生成以下错误:

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

操作系统:Android 11 应用程序:Cxxdroid

如果这可能有帮助

标签: c

解决方案


正确的代码是上面的。

#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\n",random_elem);
    return random_elem;
}


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

int main() {

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

    gamePlay();
}

推荐阅读