首页 > 解决方案 > 如何在 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。

标签: cstringfunctionreturncs50

解决方案


  1. 更改int mario(void);char *mario(void);

  2. 更改printf("%c", mario());printf("%s", mario());

  3. 移动char *result = " ";mario()函数的开头,使其在return.


推荐阅读