sizeof(a)
gives you the size of the pointer, not of the array of characters the pointer points to. It's the same as if you had said sizeof(char*)
.
You need to use strlen()
to compute the length of a null-terminated string (note that the length returned does not include the null terminator, so strlen("abcd")
is 4, not 5). Or, you can initialize an array with the string literal:
char a[] = "abcd";
size_t sizeof_a = sizeof(a); // sizeof_a is 5, because 'a' is an array not a pointer
The string literal "abcd"
is null terminated; all string literals are null terminated.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…