简体   繁体   中英

Explain the output of this code about pointers

#include <stdio.h>

main() {
    char *p = "Hello world";
    int *q;
    p++;

    q = (int*) p;
    q++;

    printf("\n %s\n%s", p, q);
}

The output of this program is this:

ello world
 world

Can anybody explain how this program works?

In the p++ line, you increment the address p by one, as that is the size of the byte type, so p ends up looking at the "e" in your string.

Then you assign the same address of p into q , so it also looks at "e". Then you increment q , but as it is a pointer to an integer (type int , which in your machine is 4 bytes long), it is incremented by four. So adding four to the "e" it was looking at before, it ends up looking at the space character.

char *p initially points to first character of the string Hello World . The statement p++ changes pointer p to point to second character of the string. This explains you get ello world when you print the string using pointer p after incrementing it.

When you assign the pointer p to a pointer q which is a pointer to int. Incrementing the pointer q changes the pointer to point to world (it is pointing at the space character). It is due to fact that int is 4-bytes long in your machine and incrementing a pointer to int, increments the pointer content by 4 bytes. Therefore, when you print a string using pointer q , it prints world .

it is because you have incremented the pointer variable after storing the string (p++ and q++). where's in your printf statement you are printing the whole stirng % s not just a character thats why it is printing like that. I hope you got the answer!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM