#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?
#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?
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 *
.
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.
#include <stdio.h>
int main(void){
char x [] = "hello world.";
printf("%c \n", x[0]);
return 0;
}
A string in C is an array of characters with the last character being the NULL character '\0'. When you use the "%s" string specifier in a printf, it will start printing chars at the given address, and continue until it hits a null character. To print a single character use the "%c" format string instead.
Since a string in C is an array of characters. This statement will print the first character.
printf("%c \n", "hello world."[0]);