c - 如何从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();
}
在作品printf
中getWord()
但不在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
如果这可能有帮助
解决方案
正确的代码是上面的。
#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();
}
推荐阅读
- php - 如何在 laravel 迁移中创建格式 YYYY-MM-DDTHH:MM:SS+HH:MM?
- ag-grid - 如果 Angular 有任何版本升级,我是否需要将我的 ag-grid 升级到较新的版本?
- google-cloud-platform - 如何使用脚本或 API 在项目之间导出和导入谷歌云监控仪表板?
- google-apps-script - 获取更新的工作表数据
- c# - C# WPF 应用程序 - 关闭应用程序时出现异常
- debugging - 调试 gdb tui 定义新布局
- flutter - 未定义名称 | TextEditingController 中的错误 (''Flutter/Dart)
- linux - 用于从原始套接字读取数据包的 Linux 应用程序在一段时间后停止接收数据包
- c# - Angular not sending request to API
- oracle - 带有游标的 PL/SQL 错误,ERROR ORA-06550