Urler
Urler

Reputation: 520

Invalid operands to binary + (char*) and (char*)?

Why doesn't this code just print the two strings? I'm casting 5 to (char *) so what am I doing wrong?

int *p = 5;
char * str = "msg";
printf("string is: %s" + "%s", str, (char *) p);

Upvotes: 0

Views: 2099

Answers (1)

gsamaras
gsamaras

Reputation: 73366

Your code will give a warning, like:

main.c:5:12: warning: initialization makes pointer from integer without a cast [enabled by default]

since you try to assign an integer to a pointer without a cast. Even with a cast, it will rarely be what you want, a pointer to the address you gave.

I will provide an example, were I declare a variable a initialized with 5 and then, assign its address to a pointer p.

Also, notice that C, unlike C++ and Java doesn't provide a + operator for strings. You have to use string.h library for this kind of operations.

[EDIT] (see comments, thanks to Deduplicator)

#include <stdio.h>

int main() 
{
    int a = 5;
    // Assign the address of 'a' to the pointer 'p'.
    int *p = &a;
    // Now p points to variable 'a', thus 5.
    // The value of 'p' is the address of the variable 'a'.

    char const *str = "msg";

    // print the string 'str' and the number, that 'p'
    // points to. Since `p` is of type `int*`, we expect
    // it to point to an integer, thus we use %d in the
    // printf().
    printf("string is: %s%d", str, *p);

  return 0;
}

Output:

string is: msg5

Upvotes: 2

Related Questions