C语言 如何访问字符数组的第一个字符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3845600/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:35:04  来源:igfitidea点击:

How to access the first character of a character array?

carraysindexingprintfcharacter

提问by Kay

#include <stdio.h>

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

The above code prints out "hello world."

上面的代码打印出来 "hello world."

How would i print out just "h"? Shouldn't the access x[0]ensure this?

我将如何打印出来"h"?访问不应该x[0]确保这一点吗?

回答by codaddict

You should do:

你应该做:

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

The format specifierto print a char is c. So the format string to be used is %c.

打印字符的格式说明符c. 所以要使用的格式字符串是%c.

Also to access an array element at a valid index iyou need to say array_name[i]. You should not be using the &. Using &will give you the address of the element.

另外要访问有效索引处的数组元素,i您需要说array_name[i]. 您不应该使用&. 使用&将为您提供元素的地址。

回答by John Carter

Shouldn't the access x[0]ensure this?

访问不应该x[0]确保这一点吗?

No, because the &in &x[0]gets the address of the first element of the string (so it's equivalent to just using x.

不,因为&in&x[0]获取字符串的第一个元素的地址(所以它相当于只使用x.

%swill output all the characters in a string sees the null character at the end of the string (which is implicit for literal strings).

%s将输出字符串中的所有字符看到字符串末尾的空字符(这对于文字字符串是隐式的)。

In order to print out a character rather than the whole string, use the character format specifier, %cinstead.

为了打印出一个字符而不是整个字符串,请改用字符格式说明符%c

Note that printf("%s \n", x[0]);would be invalid since x[0]is of type charand %sexpects a char *.

请注意,这printf("%s \n", x[0]);将是无效的,因为x[0]它是类型char并且%s需要一个char *.

回答by Paul Tomblin

#include <stdio.h>

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

回答by ssfrr

A string in C is an array of characters with the last character being the NULL character \0. When you use the %sstring 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 %cformat string instead.

C 中的字符串是一个字符数组,最后一个字符是 NULL 字符\0。当您%s在 a 中使用字符串说明符时printf,它将开始在给定地址打印字符,并继续直到遇到空字符。要打印单个字符,请改用%c格式字符串。

回答by sadananda salam

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

因为 C 中的字符串是一个字符数组。该语句将打印第一个字符。

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