2

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]?

3
  • 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. Commented Jan 24, 2021 at 1:38
  • 1
    No element in str1 is '\0' so your loop is going out of bounds, which is undefined behavior Commented Jan 24, 2021 at 1:39
  • 3
    You probably accessed the first array out of bound causing undefined behavior. The first array is of size 3 while the second one is 10. Commented Jan 24, 2021 at 1:39

1 Answer 1

6

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";.

Sign up to request clarification or add additional context in comments.

1 Comment

Note: 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'].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.