开发者

c programming language,pointer

#include<stdio.h>
#include<conio.h>
main()
{
    char *q[]={"black","white","red"};
    printf("%s",*q+3);
    getch();
    return 0;
}

Code gives output "ck". In this I want to know how *q+3 expression is evaluated. Means first *q is evaluated then 3 is added to what *q points to. In case of integer array it is si开发者_开发问答mple to realise but here *q points to "black" then 3 is added in what?


q is dereferenced, pointing to q[0]. This is a pointer to the string literal "black". You then add three, making it point to the 'c' in "black". When passed as a string, printf() interprets it as "ck".

What else don't you understand?


A char*[] is an array of char*. That is, each element in q is a char*. So when you do *q you get a pointer to "black", much as if you had done this:

char const * str = "black";

Thus if you add 3 you are moving inside the string, up to the character "c", thus it prints "ck".


*q points to the address of the memory containing 'b'. For example, suppose this address is 100 in the memory. Adding 3 gives 103 where 'c' is stored.

When you define a string using "..." in C, it has '\0' or 0 at the end of all characters automatically, and C uses this null character to detect the end of a string. In your case, the address 105 contains '\0'.

That is, it prints only the characters in 103 and 104: "ck".


the *-dereferencer knows (by the compiler) how big it is, and if you add a value, you jump to the next location according to the type of the value.

so int*p; *p+3 move three ints (sizeof(int)) ahead. (*p)+3 gives the value under p and adds three.


A very good resource when you have questions about C/C++ is http://www.cplusplus.com/.

The article about pointers is here: http://www.cplusplus.com/doc/tutorial/pointers/.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜