C 编程:为什么这个示例行可以在数组末尾没有 '0' 或 '\0' 字符?

C Programming: Why Can This Sample Line Have Not '0' OR '\0' Character At The End Of The Array?

我还是个C编程新手

我听说字符串总是以'0'或'\0'作为最后一个字符。

那我有一个问题。为什么下面的示例行在最后一个位置有'5'?

为什么不是“0”或“\0”?

int myArray[10] = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 };

上面那行来自How to initialize all members of an array to the same value?

char cArr1[] = {'a', 'b', 'c'};
char cArr2[] = "def";
int iArr3[] = {1, 2, 3};
int iArr4[5] = {1, 2, 3};

memory layout
=============
var name    memory address    value
cArr1       AAAA0000          'a'
            AAAA0001          'b'
            AAAA0002          'c'
            AAAA0003          unknown (may have a '[=10=]' by chance)
            ...
cArr2       BBBB0000          'd'
            BBBB0001          'e'
            BBBB0002          'f'
            BBBB0003          '[=10=]' is inserted by the compiler
            ...
iArr3       CCCC0000          1
            CCCC0004          2
            CCCC0008          3
            CCCC000C          unknown (may have any value)
            ...
iArr4       DDDD0000          1
            DDDD0004          2
            DDDD0008          3
            DDDD000C          0 (not defined explicitly; initialized to 0)
            DDDD0010          0 (not defined explicitly; initialized to 0)
            ...

"Why can this sample line have not 0 OR '[=11=]' character at the end of the array?"

因为myArrayint的数组(而且不包含字符串)!空终止符(用于字符串)只能应用于 char,但不能应用于 int 数组。

甚至 char 的数组本身也不是空终止符。只有当 char 的数组应该包含一个 字符串 并且您想将数组的内容用作字符串时,才需要空终止符。

除此之外,int 数组当然可以在最后一个元素内保存 int0,但您目前在这里混合了两种不同的东西。

字符串是字符数组,其实际元素以零字符结尾。大多数标准 C 字符串函数都遵循此约定。

这个

int myArray[10] = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 };

是一个整型数组。零是一个有效的整数值。在其他整数值中,它经常用作数组的实际值。

当然你可以让零成为整数数组的标记值。但是没有使用零作为整数数组标记值的标准 C 函数。