-1

I dont understand how the word "word" is printed in line 5. Can somebody explain to me?

    #include <stdio.h>
    int main(void) {
        char str[50] = "hello\0 worl\bd";
        printf("\n %s ",str);
        printf("%s \n",str+str[4]-*str);
        return 0;
    }
Blaze
  • 16,736
  • 2
  • 25
  • 44
Henrick
  • 81
  • 5

2 Answers2

3

So, step-by-step:

  • "str" points to your string "hello\0 worl\bd", which is actually "hello\0 word" (since \b deletes the previous character)

  • *str = is the the "content" of your char pointer, which means the first character of your string, that is "h"

  • str[4] = is the (4+1)th character of str, that is 'o'

  • str[4] - *str = 'o'-'h' = 7 (but why is it 7? 'h' has an ASCII character value of 104 and 'o' a value of 111)

  • str + 7 = str[7]


So, you are basically printing the string starting at index:7 of your initial string.

Hence: 'word' ;)

Dr.Kameleon
  • 22,532
  • 20
  • 115
  • 223
1

First of All the String as under:

 0 => h
 1 => e
 2 => l
 3 => l
 4 => o
 5 => \0
 6 => (space bar)
 7 => w
 8 => o
 9 => r
10 => l
11 => \b
12 => d

now your command is:

printf("%s \n",str+str[4]-*str);

C has done the following thing

 str => point of starting printing

 str[4] as above is o

 *str as above is h

 Thus o - h = 7 [i.e. ascii value 111 - 104]

 printing would starting from character 7 i.e. [str+7]
Vineet1982
  • 7,730
  • 4
  • 32
  • 67