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 Answer
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";.
1 Comment
char str[] = "abc"; is initialization syntax, not assignment. So we can do modification like str[2] = 'd'; to make str becomes ['a', 'b', 'd', '\0'].
char str1[] = {'a','b','c'}, allocates an array of chars with size 3.char str2[10]allocates an array of size 10 and you set indexes 0,1,2 with your desired values. The rest are still allocated and available for use, though contain garbage values.str1is'\0'so your loop is going out of bounds, which is undefined behavior