Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the "NUL" character ("\0") byte separated or is it assigned to that char-array with the string?

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?

like image 311
RobertS supports Monica Cellio Avatar asked Sep 30 '19 10:09

RobertS supports Monica Cellio


1 Answers

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 ]

like image 199
melpomene Avatar answered Nov 02 '22 04:11

melpomene