Search code examples
cpointersc-stringsstrcpypointer-arithmetic

Pointer seems not be sync with printf's output


I have trouble understanding what pointer2 contains. The second printf prints llo World, but the third one prints Hey you guys!. Why would it be like that if strcpy copies y you guys!\n into llo World. From my understanding of the below program the last output supposed to be llo Worldy you guys!\n, isn't it?

int main() 
{
    char str_a[20];  // a 20 element character array
    char *pointer;   // a pointer, meant for a character array
    char *pointer2;  // and yet another one

    strcpy(str_a, "Hello World\n");

    pointer = str_a; // set the first pointer to the start of the array
    printf("%p\n", pointer);

    pointer2 = pointer + 2; // set the second one 2 bytes further in
    printf("%s", pointer2);       // print it

    strcpy(pointer2, "y you guys!\n"); // copy into that spot
    printf("%s", pointer);        // print again
}

Solution

  • The pointer pointer points to the first character of the array str_a.

    pointer = str_a;
    

    The array contains the string "Hello World\n".

    The pointer pointer2 points to the third element of the string

    pointer2 = pointer + 2;
    

    that is it points to "llo World\n".

    Then this substring is overwritten keeping unchanged str_a[0] and str_a[1].

    strcpy(pointer2, "y you guys!\n");
    

    So the array str_a contains the string "Hey you guys!\n"

    In fact the above call of strcpy is equivalent to

    strcpy( &str_a[2], "y you guys!\n");
    

    because in turn this statement

    pointer2 = pointer + 2;
    

    is equivalent to

    pointer2 = &str_a[2];
    

    or

    pointer2 = &pointer[2];
    

    And this call

    printf("%s", pointer); 
    

    outputs the string.

    That is "He" (starting from str_a[0]) plus "y you guys!\n" (starting from str_a[2])yields the result string.