Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Character string declaration with static size

I was trying different ways to declare a string in C for exam preparation. We know that string in C is character array with '\0' at end. Then I found that even if I declare an array of 5 characters and put 5 characters in it like "abcde" it is accepted. Then where is the null char stored?

I declared strings in following ways

char str[] = {'a','b','c','d','e'};
char str2[] = "abcde";
char str3[5] = "abcde";

Now, in the 3rd case, I am allocating 5 byte of space and I have exactly 5 characters in the array, then if string should have a null character at end where is it being stored? Or is it the case that null is not appended? What about the 1st and 2nd cases, are null appended there? strlen() returns 5 in all 3 cases.

like image 785
Kushal Mondal Avatar asked Dec 08 '25 09:12

Kushal Mondal


2 Answers

The NUL character is stored only in the second example

char str2[] = "abcde";

where the array is sized automatically to include it. An array of characters does not have to be a string, and the other two are encoded without the NUL terminator.

If the code happens to treat them correctly as strings, that was an unfortunate result of undefined behaviour.

#include <stdio.h>

int main(int argc, char *argv[])
{
    char str[] = {'a','b','c','d','e'};
    char str2[] = "abcde";
    char str3[5] = "abcde";
    printf("%zu\n", sizeof str);
    printf("%zu\n", sizeof str2);
    printf("%zu\n", sizeof str3);
}

Program output:

5
6
5
like image 116
Weather Vane Avatar answered Dec 11 '25 11:12

Weather Vane


In the third case, the null terminator is not appended. From the documentation:

If the size of the array is known, it may be one less than the size of the string literal, in which case the terminating null character is ignored:

So when you check its length with strlen, you get undefined behavior (and the the same when you try it with the first one, since that also isn't a string).

Any less that that is not allowed, (for me on MSVC it shows an error but still compiles it, for some reason). More than the string length is allowed, in which case the rest is zero-initialized.

like image 32
Blaze Avatar answered Dec 11 '25 12:12

Blaze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!