Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 731
Kay Avatar asked Oct 25 '25 06:10

Kay


2 Answers

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.

like image 112
codaddict Avatar answered Oct 26 '25 20:10

codaddict


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

like image 33
John Carter Avatar answered Oct 26 '25 20:10

John Carter