Search code examples
cpointerspointer-arithmeticpost-incrementpre-increment

Incrementing pointer on string results in pointer to char not on string


I've got this code to get familiar with C:

char txt[] = "Thanksfor4lltheFish";
char *ptr = &txt[2];

printf("%c\n", ++*ptr++);

I expected to increase the pointer by 2 and print "k" but I get "b" which isn't even in this string. Why?


Solution

  • After this code snippet

    char txt[] = "Thanksfor4lltheFish";
    char *ptr = &txt[2];
    

    the pointer ptr points to the third character of the array text that is to the character 'a'.

    This expression

    ++*ptr++
    

    logically is equivalent to the following sequence of statements

    char *tmp = ptr;
    ++ptr;
    char c = *tmp;
    ++c;
    

    As a result the character 'a' pointed to by the pointer ptr is incremented and you get the character 'b'.

    The value of the expression with the post-increment operator

    ptr++
    

    is the value of the pointer ptr before incrementing it. That is you get the address of the character 'a'. Then this temporary expression with the address of the character 'a' is dereferenced

    *ptr++
    

    and you get the character 'a' itself that in turn is incremented

    ++*ptr++
    

    That is the first post-increment operator is applied to the pointer ptr. The second pre-increment operator is applied to the pointed character 'a' after dereferencing the value returned by the first post-increment operator.

    If you wanted to get the expected by you result you could use the following expression in the call of printf

    *( ptr += 2 )
    

    In C++ (but not in C) you may also write

    *++++ptr