c - 如何在 C 中返回字符串?
问题描述
所以我试图在哈佛 CS50 课程上做一道题。我能够创建该程序,但希望在设计方面使其更简洁。我决定使用一个函数。
目标是创建一个程序,其高度值介于 1 和 8 之间。如果高度为 1,则输出为# #
. 如果高度增加,则输出将包括另外 2 名球员,#
左右各有 1 名球员。
当我尝试返回一个值并创建一个返回类型为 的函数时string
,我不断收到错误消息。
代码:
#include <stdio.h>
#include <cs50.h>
char *mario();
int main(void){
printf("%c", mario());
}
char *mario(){
int stop = 0;
while(stop == 0){
unsigned int height = get_int("Height: ");
char *result = " ";
if(height == 1){
printf("\n# #\n");
stop = 1;
}else if(height == 2){
result = "\n # #\n## ##\n";
stop = 1;
}else if(height == 3){
result = "\n # #\n ## ##\n### ###\n";
stop = 1;
}else if(height == 4){
result = "\n # #\n ## ##\n ### ###\n#### ####\n";
stop = 1;
}else if(height == 5){
result = "\n # #\n ## ##\n ### ###\n #### ####\n##### #####\n";
stop = 1;
}else if(height == 6){
result = "\n # #\n ## ##\n ### ###\n #### ####\n ##### #####\n###### ######\n";
stop = 1;
}else if(height == 7){
result = "\n # #\n ## ##\n ### ###\n #### ####\n ##### #####\n ###### ######\n####### #######\n";
stop = 1;
}else if(height == 8){
result = "\n # #\n ## ##\n ### ###\n #### ####\n ##### #####\n ###### ######\n ####### #######\n######## ########\n";
stop = 1;
}
}
return result;
}
错误:
mario.c:33:7: error: conflicting types for 'mario'
char *mario(){
^
mario.c:5:5: note: previous declaration is here
int mario(void);
^
mario.c:88:12: error: use of undeclared identifier 'result'
return result;
^
2 errors generated.
<builtin>: recipe for target 'mario' failed
make: *** [mario] Error 1
我怎样才能解决这个问题?
我正在使用 CS50 的库和 IDE。
解决方案
更改
int mario(void);
为char *mario(void);
更改
printf("%c", mario());
为printf("%s", mario());
移动
char *result = " ";
到mario()
函数的开头,使其在return
.
推荐阅读
- python - 如何在熊猫中将一行的条件插入另一行?
- oxygenxml - 使用 xproc 文件,如何在氧气中逐步调试/跟踪?
- java - 有没有办法在序列化过程中将“.0”保留在数字上?
- python - Pandas 将 JSON 字符串转换为 Dataframe - Python
- python - 不断收到 python ModuleNotFoundError: No module named
- google-colaboratory - 错误无法加载显示输出所需的 JavaScript 文件
- javascript - 用 actioncable 区分发送和接收
- react-native - Animated TextInput dismisses the keyboard after each character
- wpf - 打印到 PDF 时 WPF DocumentViewer.Print 失败,但仅来自我的应用程序
- python - Hwo用多行多列实现QFormLayout