Arrays C编程:用两种不同的方法初始化字符数组

Arrays C编程:用两种不同的方法初始化字符数组,arrays,c,char,Arrays,C,Char,我正在学习C语言中的数组。当使用字符数组时,这两个语句之间有什么区别 char my_char_数组[]={M','y','S','t','r','i','n','g'} 及 char my_char_array[]=“我的字符串” 另外,如果我尝试将我的\u char\u数组的值打印到屏幕上,为什么会得到一些不可打印的字符(这种情况发生在我的\u char\u数组被双向初始化的情况下) printf(“我的字符数组[]的值:%s\n”,我的字符数组) my_char_数组[]的值:my字符串╠

我正在学习C语言中的数组。当使用字符数组时,这两个语句之间有什么区别

char my_char_数组[]={M','y','S','t','r','i','n','g'}

char my_char_array[]=“我的字符串”

另外,如果我尝试将我的\u char\u数组的值打印到屏幕上,为什么会得到一些不可打印的字符(这种情况发生在我的\u char\u数组被双向初始化的情况下)

printf(“我的字符数组[]的值:%s\n”,我的字符数组)

my_char_数组[]的值:my字符串╠╠╠╠╠╠╠╠╠╠╠

char v1[] = {'M','y',' ','S','t','r','i','n','g'};
char v2[] = "My String";

v2比v1长一个字节,最后一个字节包含许多API(包括printf的%s)用来确定c字符串结尾的空字符。

这两个数组的主要区别是字符串终止字符
\0
。 阵列

char my_char_array[] = {'M','y',' ','S','t','r','i','n','g'};
结尾没有字符串终止字符。因此,
printf
将继续打印,直到到达
\0
。但是,C编译器会自动为以下数组插入字符串终止字符:

char my_char_array[] = "My String";
简言之

char my_char_array1[] = {'M','y',' ','S','t','r','i','n','g'};
char my_char_array2[] = "My String";
// are not equivalent
但是,


与其他提到的答案一样,
\0
是主要区别

char my_char_数组[]={M','y','S','t','r','i','n','g'}

此语句定义一个
char
数组。鉴于本声明

char my_char_array[]=“我的字符串”

定义一个
字符串
,在C语言中,该字符串也是一个
字符
数组,但末尾有一个额外的
\0
字符

i、 e

是相等的,但

char my_char_array[] = {'M', 'y', ' ', 'S', 't', 'r', 'i', 'n', 'g'};
char my_char_array[] = "My String";

不是。对于输出,不能使用
%s
格式说明符打印字符数组。您需要按元素访问它。

您可能需要先检查这些链接

  • 类似问题:
  • C11文件:
我搜索了C11文档(你可以从上面的链接获得文档),它说

6.7.9 Initialization

... skipped
14
An array of character type may be initialized by a character string
literal or UTF −8 string literal, optionally enclosed in braces.
Successive bytes of the string literal (including the terminating null
character if there is room or if the array is of unknown size) initialize
the elements of the array.

22
If an array of unknown size is initialized, its size is determined by
the largest indexed element with an explicit initializer. The array type
is completed at the end of its initializer list.
char my_char_array1[]={M','y','S','t','r','i','n','g'};
char my_char_array2[]=“我的字符串”;
my\u char\u array1
变量大小未知。所以,总大小是最后一个“g”初始值设定项。没有显式以null结尾的

my_char\u array2
变量的大小也是未知的,但是,连续字节包括数组末尾的空字节


printf
该函数处理以null结尾的字符数组。它可以打印字符,直到满足空字节。这就是为什么会有奇怪的字符。

第二个字符有一个额外的字节作为空终止符。i、 第一个是未终止的,当您尝试使用期望以null结尾的字符串的函数打印它时,会得到未定义的行为。
char my_char_array[] = {'M', 'y', ' ', 'S', 't', 'r', 'i', 'n', 'g'};
char my_char_array[] = "My String";
6.7.9 Initialization

... skipped
14
An array of character type may be initialized by a character string
literal or UTF −8 string literal, optionally enclosed in braces.
Successive bytes of the string literal (including the terminating null
character if there is room or if the array is of unknown size) initialize
the elements of the array.

22
If an array of unknown size is initialized, its size is determined by
the largest indexed element with an explicit initializer. The array type
is completed at the end of its initializer list.