2
#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?

Community
  • 1
  • 1
  • 8
    `a` and `b` are not _strings_ as they both lack a _null character_ as required by `strlen()`. – chux - Reinstate Monica May 22 '20 at 02:33
  • This is [your code in action](https://www.jdoodle.com/embed/v0/25x8) – PM 77-1 May 22 '20 at 02:47
  • I also thought of coincidence and tried several times. – PM 77-1 May 22 '20 at 02:50
  • 1
    @isrnick - I agree that this is undefined behavior. – PM 77-1 May 22 '20 at 02:57
  • `GCC 5.3.0` produces what OP described, `GCC 9.1.0` - gives the same value of 54 for both.. – PM 77-1 May 22 '20 at 03:00
  • 1
    An array of size `N` can store at maximum a string with `N-1` non-null characters plus the null character that signals the end of the string. So, since your arrays have size 50, your for loop should go up to `j<49`, and after the loop there should be assignments of the null characters to position 49 in both arrays `b[49]='\0'; a[49]='\0';` . – isrnick May 22 '20 at 03:04

1 Answers1

1

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.

Marco
  • 7,007
  • 2
  • 19
  • 49