If i define a string:
char array[5] = {"hello"};
Is the NUL character (\0) byte "hidden" added to "array[5]", so that the array is not contained of 5 bytes in memory, it is contained of 6 bytes?
OR does the NUL character byte lie "separated" from "array[5]" in memory only after the last element of the char-array, but not directly assigned to "array[5]"?
If i would put this:
i = strlen(array);
printf("The Amount of bytes preserved for array: %d",i);
What would be the result for the amount of bytes preserved for array[5]?
Does the "NUL" character ("\0") byte lie separated after the last element of char-array in the memory or is it assigned to that char-array?
Does the "NUL" character ("\0") byte lie separated after the last element of char-array in the memory or is it assigned to that char-array?
No. Neither answer is correct. See below for details.
Answer for C:
If you write your code like that, with an explicit size that is too small for the terminator, array
will have exactly 5 elements and there will be no NUL character.
strlen(array)
has undefined behavior because array
is not a string (it has no terminator). char array[5] = {"hello"};
is equivalent to char array[5] = {'h', 'e', 'l', 'l', 'o'};
.
On the other hand, if you write
char array[] = "hello";
it is equivalent to
char array[6] = {'h', 'e', 'l', 'l', 'o', '\0'};
and strlen
will report 5
.
The relevant part of the C standard is:
An array of character type may be initialized by a character string literal, optionally enclosed in braces. Successive characters of the character 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.
(Emphasis mine.)
Answer for C++:
Your code is invalid. [dcl.init.string] states:
There shall not be more initializers than there are array elements. [ Example:
char cv[4] = "asdf"; // error
is ill-formed since there is no space for the implied trailing
'\0'
. — end example ]
In C++, char array[5] = {"hello"}
is of six bytes. But you have assigned five bytes only. Therefore, the array declaration is incorrect.
Alternatively, this works: char array[6] = {"hello"}
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.