char *a = "apple";
printf("%s\n", a); // fine
printf("%s\n", a[1]); // compiler complains an int is being passed
Why does indexing a string pointer give me an int? I was expecting it to just print the string starting at position one (which is actually what happens when i use &a[1]
instead). why do i need to get the address?
That's just how the []
operator is defined - a[1]
, when a
is a char *
, fetches the next char
after the one pointed to by a
(a[0]
is the first one).
The second part of the puzzle is that char
values are always promoted to int
(or rarely, unsigned int
) when passed as part of a function's variable-length argument list.
a
is equivalent to &a[0]
, and it prints from the first character - so it makes sense that &a[1]
would print starting from the second character. You can also just use a + 1
- that's completely equivalent.
If you use the %c
conversion specifier, which prints a single character, you can use a[1]
to print just the second character:
printf("%c\n", a[1]);
The expression a[1]
yields a single char, and in expressions that is widened to an int.
You can print a char with %c
:
char *a = "apple";
printf("%c\n", a[1]); // prints 'p'
You can achieve what you want by using a+1
, like
printf("%s\n", a+1); // prints 'pple'
An other way to explain this:
char *a2 = a+1; // a2 points to 'pple'
a[1] ≡ *(a+1) ≡ *a2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With