cstrlen

Why strlen() is giving wrong value for a char array with undefined array size?


#include<stdio.h>
#include<string.h>
int main(){
  int a[]={1,2,3,4};
  int size= sizeof(a)/sizeof(int);
  printf("\nSize/capacity of integer type array(with no limit) %d\n",size);

  int a1[6]={1,2,3,4};
  int size1= sizeof(a1)/sizeof(int);
  printf("\nSize/capacity of integer type array(with a limit of 7) %d\n",size1);

printf("\n");

  char b[7]={'a','b','c','d','e'};
  int size2= sizeof(b)/sizeof(char);
  int length=strlen(b);
  printf("\nSize/capacity of char type array(with a limit of 7) %d\n",size2);
  printf("\nNumber of char type data in the array %d\n",length);

  char br[]={'k','l'};
  int size3= sizeof(br)/sizeof(char);
  int length1=strlen(br);
  printf("\nSize/capacity of char type array(with no limit) %d\n",size3);
  printf("\nNumber of char type data in the array length1 %d\n",length1);    //answer should have been 2

 return 0;
}`

It gave me 7 as an output for the value length1. When I commented out the upper block(above the initialization of br[]) the array length came out as 3. I want to know why this is happening and the solution. I am new to this but thanks in advance.

The output for the code above:

Size/capacity of integer type array(with no limit) 4

Size/capacity of integer type array(with a limit of 7) 6

Size/capacity of char type array(with a limit of 7) 7

Number of char type data in the array 5

Size/capacity of char type array(with no limit) 2

Number of char type data in the array length1 7


Solution

  • strlen works by looking for the null terminator '\0', and your character arrays don't end with a null terminator character.

    Change this

    char br[]={'k','l'};
    

    to this

    char br[]={'k','l', '\0'};
    

    and make a similar change to b (plus adding 1 to the size of the array) and see what happens.