Jackdon Chew
Jackdon Chew

Reputation: 135

C program printf char with string array

#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

Upvotes: 0

Views: 673

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 595377

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

Upvotes: 3

Related Questions