Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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");

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading