char str1[] = {'a', 'b', 'c'};
creates an array of 3 characters, with the values 'a'
, 'b'
, and 'c'
. The size of the array is 3, which you can see with sizeof str1
(this returns the number of bytes, but as a char
is defined to be 1 byte it's the same as the number of elements). Trying to calculate the length of the string contained in this array causes undefined behavior, since str1
does not contain a C-style string as it has no ''
terminator. Your loop calculating this goes out of the bounds of the array.
char str2[10] = {'a', 'b', 'c'};
creates an array of 10 characters, with the values 'a'
, 'b'
, 'c'
, and 7 ''
s. The size of the array is 10. Calculating the length of the string in str2
gives you 3, since str2[3]
is ''
;
If you want to create an array containing a C-style string without specifying the size, you can do char str[] = {'a', 'b', 'c', ''};
, or more simply, char str[] = "abc";
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…