So I was trying to do a problem set on the Harvard CS50 course. I was able to create the program but wanted to make it cleaner in terms of design. I decided to use a function.
The goal was to create a program that takes the height value that is between 1 and 8. If the height was 1, then the output would be # #
. If the height increased, then the output would include 2 more players with 1 extra #
to the left and right.
When I tried to return a value and create a function with a return type of string
, I kept getting errors.
Code:
#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;
}
Error:
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
How can I fix this?
I am using CS50's library as seen and the IDE.
Change int mario(void);
to char *mario(void);
Change printf("%c", mario());
to printf("%s", mario());
Move char *result = " ";
to the start of the mario()
function so it is in-scope for return
.