2

Consider the following:

char abc[14] = "C Programming"; printf("%s", abc + abc[3] - abc[4]);

The output of the above printf statement is "rogramming". I can't seem to figure how this output is obtained.

2 Answers 2

5

Because chars are a form of integers.

    abc + abc[3] - abc[4]
==> abc + 'r' - 'o'
==> abc + 3

And thus you print the string abc starting at index 3.

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

7 Comments

Sorry bro :( but what you said is not true.
@GRC Why don't you share your thoughts :)
The fact that chars have numerical value does not have to do with what he did. @Hacks wrote right answer.
@GRC He wrote exactly the same thing. I quote: 'r' - 'o' = 3
He (@GRC) is talking about pointer arithmetic which is addressed in my answer.
|
4

abc is an array. When used in expression, in most cases, it converted to pointer to its first element. abc[3] is a char which is 'r'. abc[4] is 'o'. abc[3] - abc[4] = 'r' - 'o' = 3. abc + 3 = &abc[3].
So, the expression abc + abc[3] - abc[4] is equivalent to pointer to 3rd charater of string "C Programming".

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.