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], whenais achar *, fetches the nextcharafter the one pointed to bya(a[0]is the first one).The second part of the puzzle is that
charvalues are always promoted toint(or rarely,unsigned int) when passed as part of a function’s variable-length argument list.ais 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 usea + 1– that’s completely equivalent.If you use the
%cconversion specifier, which prints a single character, you can usea[1]to print just the second character: