FRANCIS CASIMIR S
FRANCIS CASIMIR S

Reputation: 49

Why the function strlen() returns different values for the same length of two char arrays?

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

int main() {
    
    char a[50],b[50];// same sized arrays

    for(int j =0;j<50;j++){
        b[j]='b';a[j]='a';// initializing with the same number of elements
    }

    printf("the size of a is %ld,",strlen(a));
    printf("the size of B is %ld",strlen(b));

    return 0;
}

The output is

the size of a is 50, the size of B is 54

But what i expect is the size of a is 50 the size of B is 50

what is the problem here?

Upvotes: 2

Views: 412

Answers (1)

Marco
Marco

Reputation: 7261

what is the problem here?

The problem is that you don't terminate your strings.

C requires strings to be null terminated:

The length of a C string is found by searching for the (first) NUL byte. This can be slow as it takes O(n) (linear time) with respect to the string length. It also means that a string cannot contain a NUL character (there is a NUL in memory, but it is after the last character, not "in" the string).

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

int main() {

    char a[50],b[50];// same sized arrays

    for(int j =0;j<50;j++){
        b[j]='b';a[j]='a';// initializing with the same number of elements
    }

    // Terminate strings
    a[49] = b[49] = 0;

    printf("the size of a is %ld,",strlen(a));
    printf("the size of B is %ld",strlen(b));

    return 0;
}

Gives the correct result.

Upvotes: 1

Related Questions