DollarAkshay
DollarAkshay

Reputation: 2122

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 ?

Upvotes: 1

Views: 4226

Answers (2)

OldSchool
OldSchool

Reputation: 2183

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

Upvotes: 2

unwind
unwind

Reputation: 400039

It's just basic pointer arithmetic.

The type of a string literal is pointer to character, so you can add an offset to that pointer to get the "tail" of the string. The fact that this occurs "inside a function" doesn't matter.

Your test didn't work since you cannot initialize an array from an expression like that, it has to be a "bare" string literal.

Upvotes: 2

Related Questions