0
#include <stdio.h>

char world[] = "HelloProgrammingWorld";
int main()
{
    printf("%s", world + world[6] - world[8]);

    return 0;
}

The output will be mmingWorld.

I knew the "world" will be store in memory something like this.

0x6295616             H    world[0]
0x6295617             e
0x6295618             l
0x6295619             l
0x6295620             o
0x6295621             P
0x6295622             r    world[6]
0x6295623             o
0x6295624             g    world[8]
0x6295625             r
0x6295626             a
0x6295627             m
0x6295628             m
0x6295629             i
0x6295630             n
0x6295631             g
0x6295632             W
0x6295633             o
0x6295634             r
0x6295635             l
0x6295636             d

But what is the formula to calculate the output to "mmingWorld". I had try several method and still cannot reach that word.

I compile using this https://www.onlinegdb.com/online_c_compiler

7
  • world[6] = 'r' and world[8] = 'g' Commented Nov 26, 2020 at 1:03
  • I'm not sure what you mean by a "formula". It's just counting letters. The string you want starts 11 characters into the array, so you want world+11. Commented Nov 26, 2020 at 1:04
  • @DanielWalker world[6] - world[8] (aka 'r' - 'g') is 11, not 2. Commented Nov 26, 2020 at 1:05
  • Yeah, I wasn't thinking. I was thinking about &world[6] - &world[8]. Commented Nov 26, 2020 at 1:05
  • 1
    @DanielWalker that would still not be 2, it would be undefined (out of bounds). &world[8] - &world[6] would be 2. Commented Nov 26, 2020 at 1:11

1 Answer 1

3

world[6] is the character 'r' in the string, and world[8] is the character 'g' in the string. In ASCII, 'r' has a numeric value of 114, and 'g' has a numeric value of 103.

When you refer to a fixed array by name, it decays into a pointer to the 1st element of the array.

So, you are basically taking a char* pointer to the 1st character in the string, and using pointer arithmetic to advance that pointer forward 114 - 103 = 11 number of characters in the string. Thus you are effectively passing &world[11] to printf(), hense the output "mmingWorld".

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

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.