AbsoluteSith
AbsoluteSith

Reputation: 1967

Can somebody explain to me what is happening in the given code?

   #include<stdio.h>
    int main()
    {
        char s[]="chomsky the great";
        printf("try0 %s\n",s+s[3]-s[9]);    
        printf("try1 %s\n",s+s[3]-s[1]);
        return 0;
    }   

o/p in gcc compiler is

        try0 ky the great
        try1 ky the great

i'm not able to track what the program is actually doing here or rather how the compiler is working.

Upvotes: 3

Views: 103

Answers (3)

Johnny Mnemonic
Johnny Mnemonic

Reputation: 3922

The char type in C can also be treated like integer type.

s is a pointer to the first character in the string. s[3]-s[9] substracts the ASCII codes of the character on 3rd place and the character on 9th place and returns some number.

Later that number is added to the pointer to the first char in the string (s+s[3]-s[9]) and results in address that is on 5 positions past the start of the string .

When you pass that address to the printf() function it prints the string from that address to the end of the string.

Upvotes: 3

user1944441
user1944441

Reputation:

s+s[3]-s[9] = s + *(s+3) - *(s+9) = s + 'm'- 'h' = s + 109 - 104 =  s + 5 = s[5] 

So the printf starts printing at s[5]

examples what printf prints:

printf("%s",s) = chomsky the great

printf("%s",s[0]) = chomsky the great

printf("%s",s[2]) = omsky the great

printf("%s",s[5]) = ky the great

Upvotes: 4

William Pursell
William Pursell

Reputation: 212634

s[3] is m. s[9] and s[1] are both h. m - h is 5. s[5] is the k in chomsky. s + s[3] - s[9] is s + 5 which is the string starting at the k in chmosky.

Upvotes: 3

Related Questions