Change string using function parameter

Asked

Viewed 119 times

0

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void menu_principal(char* monstro1, char* monstro2){
    int escolha;
    char monstro[20];
    printf("King of Tokyo\n\n");
    printf("Jogador escolha um monstro:\n---------------------------\n");
    printf("1-Godzilla\n2-Feto Gigante Zumbi Nazista\n3-Pac-Man\n4-Blanca\n5-Penha\n6-Nemesis\n\n0-SAIR\n\n");
    do{
        scanf("%d", &escolha);
    }
    while(escolha<0 || escolha>6);
    if(escolha==0){
        exit(0);
    }
    printf("VOCE ESCOLHEU:");
    if(escolha==1){
        char monstro[30]="Godzilla";
        printf("%s\n\n",monstro);
    }
    else if(escolha==2){    
        char monstro[30]="Feto Gigante Zumbi Nazista";
        printf("%s\n\n",monstro);
    }
    else if(escolha==3){
        char monstro[30]="Pac-Man";
        printf("%s\n\n",monstro);
    }
    else if(escolha==4){
        char monstro[30]="Blanca";
        printf("%s\n\n",monstro);
    }
    else if(escolha==5){
        char monstro[30]="Penha";
        printf("%s\n\n",monstro);
    }
    else if(escolha==6){
        char monstro[30]="Nemesis";
        printf("%s\n\n",monstro);
    } 
    *monstro1=monstro; 
}

int main(){
    char monstromain1[30]=".";
    char monstromain2[30]="..";
    menu_principal(monstromain1,monstromain2);
    printf("%s",monstromain1);
    return 0;
}

I’m not managing to change the value of monstromain1 using the function. While running I get the error

main. c:42:14: Warning: assignment makes integer from Pointer without a cast [-Wint-Conversion] *monstro1=monster;

1 answer

0


The code is too complicated and difficult to read, this ends up making it difficult to find the problem and it is the fact that it is not copying the text to the variable you want, this must occur with strcpy(). This code is not exactly safe, but for an exercise is good:

#include <stdio.h>
#include <string.h>

void menu_principal(char *monstro1, char* monstro2){
    printf("King of Tokyo\n\n");
    printf("Jogador escolha um monstro:\n---------------------------\n");
    printf("1-Godzilla\n2-Feto Gigante Zumbi Nazista\n3-Pac-Man\n4-Blanca\n5-Penha\n6-Nemesis\n\n0-SAIR\n\n");
    int escolha;
    do { scanf("%d", &escolha); } while (escolha < 0 || escolha > 6);
    if (escolha == 0) exit(0);
    char *monstros[] = { "", "Godzilla", "Feto Gigante Zumbi Nazista", "Pac-Man", "Blanca", "Penha", "Nemesis" };
    strcpy(monstro1, monstros[escolha]);
    printf("VOCE ESCOLHEU: %s\n\n", monstro1);
}

int main(){
    char monstromain1[30]=".";
    char monstromain2[30]="..";
    menu_principal(monstromain1, monstromain2);
    printf("%s", monstromain1);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.