为什么我可以分配一个长度小于数组本身的字符串文字?

Why can I assign a string literal whose length is less than the array itself?

我有点困惑,这是允许的:

char num[6] = "a";

这里发生了什么?我是将指针分配给数组还是将文字值复制到数组中(因此我可以稍后修改它们)?

这种声明是一种特殊的语法糖。相当于

char num[6] = {'a', 0}

数组总是可以修改的。在这样的声明之后它的内容将是一个代表 'a' 的字符,一个零(NUL 终止符)并且数组的其余部分也将被归零(零初始化)。

char num[6] = "a";

相当于

char num[6] = {'a', '[=11=]', '[=11=]', '[=11=]', '[=11=]', '[=11=]'};
  1. Why can I assign a string literal less than the array itself? What is happening here?

这个定义很明确。当initialize character arrays with string literal,

If the size of the array is specified and it is larger than the number of characters in the string literal, the remaining characters are zero-initialized.

所以,

char num[6] = "a";
// equivalent to char num[6] = {'a', '[=10=]', '[=10=]', '[=10=]', '[=10=]', '[=10=]'};
  1. Am I assigning a pointer to the array or copying the literal values into the array (and therefore I'm able to modify them later)?

值为copied,即数组的元素将由字符串字面量(包括'[=11=]')的字符初始化。

String literals can be used to initialize character arrays. If an array is initialized like char str[] = "foo";, str will contain a copy of the string "foo".

Successive characters of the string literal (which includes the implicit terminating null character) initialize the elements of the array.

只需使用char num[6] = {"a"};。有效。

Why can I assign a string literal less than the array itself?

这是语言允许的。稍后能够向数组添加更多字符通常很有用,如果现有字符填满整个数组,这将是不可能的。

Am I assigning a pointer to the array

没有。您不能将指针分配给数组,因此不会发生这种情况。

or copying the literal values into the array

这正是正在发生的事情。

and therefore I'm able to modify them later

确实可以修改数组。

这是一种声明,等同于

char num[6] = {'a','[=10=]'};

您声明了最大长度的 C 字符串。 5 个普通字符,最后必须用 \0 来结束 c - 字符串。

有了声明就可以使用

char num[6] = "a";

那么你需要赋值:

  1. strcpy(dest,src)

    strcpy(num,"test");

  2. 逐个字符

    数[0]='t'; 数[1]='e'; 数[2]='s'; 数[3]='t'; num[4]='\0';