C strlen on char array

ghz 8months ago ⋅ 109 views

I'm new to programming, so I was practicing with C. Then I ran to a problem with my code:

#include <stdio.h>
#include <string.h>

int main()
{
    char a[] = "Hello";
    printf("Length of a: %lu\n", strlen(a));

    char b[] = {'H', 'e', 'l', 'l', 'o'};
    printf("Length of b: %lu\n", strlen(b));
}

I am expecting to get:

Length of a: 5
Length of b: 5

Instead, I'm getting:

Length of a: 5
Length of b: 10

I have tried different strings, but every time, b has double the length of a Why is the length of b is double of a?

Answers

The issue you're encountering arises because strlen() function in C calculates the length of a string by counting characters until it encounters a null terminator ('\0'). However, in the case of array b, you haven't explicitly included a null terminator, so strlen() continues counting until it encounters a null terminator in memory after the 'o' character you provided.

Here's why you're seeing 10 instead of 5 for the length of b:

  1. The characters 'H', 'e', 'l', 'l', 'o' in array b are counted normally by strlen().
  2. After 'o', strlen() keeps counting until it finds a null terminator, which could be located anywhere in memory. This leads to an incorrect length calculation.

To fix this issue, you can explicitly add a null terminator at the end of array b. Here's how you can modify your code:

#include <stdio.h>
#include <string.h>

int main()
{
    char a[] = "Hello";
    printf("Length of a: %lu\n", strlen(a)); // Outputs: Length of a: 5

    char b[] = {'H', 'e', 'l', 'l', 'o', '\0'}; // Add null terminator explicitly
    printf("Length of b: %lu\n", strlen(b)); // Outputs: Length of b: 5

    return 0;
}

By adding '\0' at the end of array b, strlen() will correctly calculate the length of the string as 5, as expected.