简体   繁体   中英

Print out a single character from a character string in C

My problem is that I only want to do a simple test for printing out a single character from a char. My code looks like the following:

#include <stdio.h>

#include <string.h>

int main()
{
    char table[20] = "Hello";

    printf("%s \n", table[0]);
    return 0;
}

I only get segementation fault, and I have also tried with curly brackets ({})

使用%c来做到这一点。

printf("%c", table[0]);

The %s format specifier expects an address to a (null terminated) string. Instead, your code passes just the ASCII value of the letter 'H' (72 in decimal) which is of course not a valid address of any string.

To print the first character:

printf("%c\n", table[0]);

To print the whole string:

printf("%s\n", table);

您需要使用%c而不是%s

Try using %c instead of %s. %s will try to print the whole string, which is not null-terminated since it was initialized as an array of characters. Without the null-termination at the end of the string, %s runs off the end and gives you a seg-fault.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM