#include <stdio.h>
int main(void){
char x [] = "hello world.";
printf("%s \n", &x[0]);
return 0;
}
The above code prints out "hello world."
How would i print out just "h"? Shouldn't the access x[0] ensure this?
You should do:
printf("%c \n", x[0]);
The format specifier to print a char is c. So the format string to be used is %c.
Also to access an array element at a valid index i you need to say array_name[i]. You should not be using the &. Using & will give you the address of the element.
Shouldn't the access
x[0]ensure this?
No, because the & in &x[0] gets the address of the first element of the string (so it's equivalent to just using x.
%s will output all the characters in a string sees the null character at the end of the string (which is implicit for literal strings).
In order to print out a character rather than the whole string, use the character format specifier, %c instead.
Note that printf("%s \n", x[0]); would be invalid since x[0] is of type char and %s expects a char *.
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