Search code examples
cstringpointersinitializationvariable-assignment

Passing a C string and using it with a local pointer


Looking at this code from The Evils of Arduino Strings

void PrintString(const char *str) {
    const char *p;
    p = str;
    while (*p) {
        Serial.print(*p);
        p++;
    }
}

I was looking at reducing/compacting it. Firstly, this seems to be equivalent:

void PrintString(const char *str) {
    const char *p;
    p = str;
    while (*p)
        Serial.print(*p++);
}

Now, looking at the first two lines, how can I combine the following two lines, is it possible?

    const char *p;
    p = str;

Can I do this?

    const char *p = str;

This would seem likely but looks unbalanced, in that there is a lack of an asterisk on the right hand side. I tried it and it seems to work but I was wondering whether it was correct, and worried that I would end up with some hard-to-track-down run-time error later on, further down the line.

However, this line below is clearly wrong (as it would change the pointer p to point to a location given by the value of the first character of the C string str):

    const char *p = *str;

Solution

  • const char *p = str;
    

    This would seem likely but looks unbalanced, in that there is a lack of an asterisk on the right hand side.

    If you separated the elements of the above snippet correctly it would not look "unbalanced" at all:

    • const char* is the type (a pointer to const characters)
    • p and str are the variables, both pointer (to const char)

    You could write the above using some unconventional layout like this:

    const char *  /* Note the lack of a semicolon */
    p = str;
    

    The above code ends up with p being defined as a pointer to char and carrying the value of str.

    You get same "result" for the below code

    const char *p;
    p = str;
    

    Note that the former is called "initialisation", whereas the latter is called "assignment".