Search code examples
cstringprintfputs

String offset inside a function


Recently I stumbled upon this strange code :

main(){
char c[] = "STRING";
puts("AKSHAY"+2);
printf("%s",c+2);
}

OUTPUT :

SHAY
RING

Can someone please explain how this offset in string works.

Also when I tried this snippet of code, I got a compilation error :

main(){
char c[] = "STRING"+2;
printf("%s",c);
}

ERROR :

Line 2: error: invalid initializer

Is it something to do with pointers ?


Solution

  • In your following code

    main(){
    char c[] = "STRING";
    puts("AKSHAY"+2);
    printf("%s",c+2);
    }
    

    What is happening here is that when you write

    char c[]="STRING";
    

    it means that c will be decayed into pointer of type char which holds the base address of "STRING" which is also of type char *.

    so when you write

    printf("%s",c+2);
    

    %s specification means it will take the base address and print the characters upto NULL( or whitespace) .so c+2 means base address +2 so thats why it is printing

    "RING"
    

    on the other hand

    puts("AKSHAY"+2);
    

    puts also take the base address and print upto NULL ( INCLUDING WHITESPACES )

    here type of "AKSHAY" is char * so adding 2 to it means changing base address to the letter S.so output is

    SHAY