Error: "invalid operands to binary expression ('char *' and 'char *')"

2

I need to create a string that contains "To Mr.:\n" and the name of the person in question ( pessoa->nome ).

char* endereca(Pessoa* pessoa)
{
    if(pessoa->sexo == 'M')
    {
        char *msg;
        msg = (char*)malloc(7*sizeof(char) + sizeof(pessoa->nome));

        msg = "Ao Sr.:\n" + pessoa->nome; //Erro aqui
    }
}
    
asked by anonymous 11.10.2016 / 18:59

2 answers

3

In C to concatenate strings you need to use strcat() . Then it would look something like this:

char* endereca(Pessoa* pessoa) {
    if (pessoa->sexo == 'M')  {
        char *msg = malloc(8 + sizeof(pessoa->nome));
        msg = strcat("Ao Sr.:\n", pessoa->nome);
    }
}

I put 8 because the string needs space for your null terminator. If you have any chance of this change, it would be best not to leave this constant size, but check the string size with sizeof . I took the sizeof de char 'because it is always 1. I took the cast because it does nothing useful.

    
11.10.2016 / 19:03
1

You're trying to add two pointers

msg = "Ao Sr.:\n" + pessoa->nome;

This is an operation that does not exist in C.

What you're probably trying to do is this here:

static const char saudacoes[] = "Ao Sr.:\n";
char* msg = malloc(sizeof(saudacoes) + strlen(pessoa->nome));
strcpy(msg, saudacoes);
strcat(msg, pessoa->nome);
    
11.10.2016 / 19:07