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

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 expected it to simply print a line starting at position 1 (which actually happens when I use &a[1] ). Why do I need to get an address?

+4
source share
5 answers

Just as the operator defines [] - a[1] when a is char * , it selects the next char after it is specified with a ( a[0] is the first one).

The second part of the puzzle is that char values ​​are always passed to int (or rarely, unsigned int ) when passed as part of the argument list of a variable variable.

a equivalent to &a[0] , and it prints from the first character - so it makes sense that &a[1] will print starting from the second character. You can also just use a + 1 - completely equivalent.

If you use the conversion specifier %c , which prints one character, you can use a[1] to print only the second character:

 printf("%c\n", a[1]); 
+13
source

Expression a[1] gives a single char, and in expressions that expand to int.
You can print char with %c :

 char *a = "apple"; printf("%c\n", a[1]); // prints 'p' 

You can achieve what you want using a+1 , for example

 printf("%s\n", a+1); // prints 'pple' 

Another way to explain this:

 char *a2 = a+1; // a2 points to 'pple' a[1] ≑ *(a+1) ≑ *a2 
+6
source

% s expects a char * pointer. Only Char is interpreted as an integer. In addition, a [1] gives you the second element, not the first!

+2
source

The characters (that is, the things that are evaluated [1]) are integers, but the formatter "% s" for printf () expects a pointer. Please note that the fact that this error was discovered at all, is an extended feature offered by some compilers, is not part of the C standard. Other compilers simply fail at runtime, possibly with a kernel dump.

+2
source
 char *a = "bla" 

a : a char* , and you should use %s for printf(...) ;

a[1] equivalent to *(a+1) , then a[1] is char , and you should use %c for printf(...) ;

&a[1] equivalent to &(*(a+1)) , then &a[1] is char* , and you should use %s for printf(...) ;

This is more like a pointer question. To better understand how pointers work, think like this:

 char *j; 

j is char*
*j is char and is equivalent to j[0]
*(j+1) is char and is equivalent to j[1]
&(*j) is a char* and equivalent with &j[0] equivalent to j
&j is char**

Another example:

 char j** 

j is char**
*j is char*
**j is char and is equivalent to *(*(j+0)+0) and is equivalent to j[0][0]
&j is char***

etc.

0
source

Source: https://habr.com/ru/post/1307260/


All Articles