What happens when I initialize a char array without setting the array size in C

Viewed 722

When I initialize a char array like char str1[] = {'a','b','c'} (array size is not set) and finding it's length using loop until str1[i] != '\0', I get length = 4. In contrast, when I initialize like char str2[10] = {'a','b','c'} (array size is set) and finding the length using using same way, I get length = 3. Why str1[3] contains a garbage value but not in str2[3]?

1 Answers

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 '\0' 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 '\0's. The size of the array is 10. Calculating the length of the string in str2 gives you 3, since str2[3] is '\0';

If you want to create an array containing a C-style string without specifying the size, you can do char str[] = {'a', 'b', 'c', '\0'};, or more simply, char str[] = "abc";.

Related