views:

87

answers:

5
#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?

+4  A: 

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 *.

therefromhere
Many thanks, i appreciate your help :)
Kay
@Kay, instead of posting a comment saying "Many thanks", try clicking the up-arrow beside the post. Also, click the checkmark beside whichever one is the best answer as well.
Paul Tomblin
+6  A: 

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.

codaddict
That did the trick!
Kay
+3  A: 
#include <stdio.h>

int main(void){
    char x [] = "hello world.";
    printf("%c \n", x[0]);
    return 0;
}
Paul Tomblin
Many thanks Paul :)
Kay
+2  A: 

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.

Spencer
A: 

Since a string in C is an array of characters. This statement will print the first character.

printf("%c \n", "hello world."[0]);
sadananda salam