Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c - why does it make sense that indexing a character pointer is an int?

Tags:

c

string

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?

like image 411
Tony Stark Avatar asked Nov 28 '22 19:11

Tony Stark


2 Answers

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]);
like image 151
caf Avatar answered Dec 15 '22 15:12

caf


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 
like image 24
Henk Holterman Avatar answered Dec 15 '22 15:12

Henk Holterman