tags:

views:

87

answers:

5
#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 simple to realise but here *q points to "black" then 3 is added in what?

+3  A: 

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?

Alexander Rafferty
u mean in such case when pointer dereferenced it return base address of char array.
avi
+2  A: 

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".

edA-qa mort-ora-y
A: 

*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".

kyu
A: 

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/.

lesderid
+1  A: 

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.

Peter Miehle