Search code examples
cpointersputs

puts() questions with const char


I'm having trouble understanding how c uses puts() to display parts of a message. Two ways which I would consider equivalent do not work the same way with the function. For example

 void skippie(char *msg)
 {
    puts(msg + 6);
 }

 char *msg = "Don't call me!";
 skippie(msg);

This compiles fine, however this does not

void skippie(char *msg)
{
    puts(msg[6]);
}

char *msg = "Don't call me!";
skippie(msg);

how does puts() distinguish between the two and only compile for one? The compiler complains that it wants a "const" char but even if I try and use that syntax it fails. Can anyone explain this?


Solution

  • The index operator also dereferences the pointer, so

    msg[6] is equivalent to *(msg + 6), not msg + 6.

    Furthermore, you cannot pass a const char* to a function, while it expects a char*. i.e., you also have to update the function signature.