如何在C语言中返回字符串?

问题描述 投票:0回答:1

所以我试图在哈佛课程上做一个问题。我能够创建该程序,但希望使其在设计方面更加简洁。我决定使用一个函数。

目标是创建一个程序,其高度值介于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。

c string function types return
1个回答
0
投票
  1. int mario(void);更改为char *mario(void);

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

  3. char *result = " ";移至mario()功能的开头,因此它在return的作用域内。

© www.soinside.com 2019 - 2024. All rights reserved.