0
#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?

1
  • You can refer to Operator precedence table. Commented Oct 10, 2010 at 9:09

5 Answers 5

3

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?

Sign up to request clarification or add additional context in comments.

1 Comment

u mean in such case when pointer dereferenced it return base address of char array.
2

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

Comments

1

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

Comments

1

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.