Error: "invalid operands to Binary Expression ('char *' and 'char *')"

Asked

Viewed 233 times

3

I need to create a string which contains "Mr: n" and the name of the person concerned (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
    }
}
  • Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site (when you have enough score).

2 answers

3

In C to concatenate strings it is necessary to use the function strcat(). So 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 in the Github for future reference.

I put 8 because the string You need space for your null terminator. If you have any chance of this changing it would be better not to leave this constant size but to check the size of the string with sizeof. I took the sizeof of char because it always is 1. I took the cast because he doesn’t do something useful, on the contrary.

2

You’re trying to put two pointers together

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

This is an operation that doesn’t exist in C.

What you’re probably trying to do is this:

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

Browser other questions tagged

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