Kay
Kay

Reputation: 845

How to access the first character of a character array?

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

Upvotes: 4

Views: 44734

Answers (5)

ssfrr
ssfrr

Reputation: 378

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.

Upvotes: 2

sadananda salam
sadananda salam

Reputation: 855

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

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

Upvotes: 0

John Carter
John Carter

Reputation: 55271

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

Upvotes: 6

Paul Tomblin
Paul Tomblin

Reputation: 182772

#include <stdio.h>

int main(void){
    char x [] = "hello world.";
    printf("%c \n", x[0]);
    return 0;
}

Upvotes: 3

codaddict
codaddict

Reputation: 454940

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.

Upvotes: 10

Related Questions