-2

I am using strlen() function to print the size of the string as shown below.

int main()

{

char c[]={1,2,3,4,5};  //same output if c[5]={1,2,3,4,5}

printf( "Length of string C is %d", strlen(c)); 


return 0; 
}

Output

Length of string C is 19

Why is it printing 19 ?

Pascal Cuoq
  • 79,187
  • 7
  • 161
  • 281
user2799508
  • 844
  • 1
  • 15
  • 41
  • 5
    Your array does not have a null terminator and so strlen is going into uninitialized memory. – Jim Rhodes Jul 26 '14 at 12:19
  • As @Jim Rhodes said you didn't put the null terminator. I also don't understand this part of the code: if c[5]={1,2,3,4,5}. Can you explain what you want to obtain? – Filo Jul 26 '14 at 12:25
  • 2
    @Filo The OP is saying that with the declaration `char c[5]={1,2,3,4,5};`, the output is the same. – Pascal Cuoq Jul 26 '14 at 12:27
  • You are right, I' reading it with a smartphone and it appears in a new line and not like a comment. Thank you – Filo Jul 26 '14 at 12:30

1 Answers1

7

In C, a string is a character array terminated with a special character '\0' (ASCII: 0).

char c[]={1,2,3,4,5}; is a character array.

To make it a string, give last value as 0, i.e. char c[]={1,2,3,4,5,0}; or better char c[]={1,2,3,4,5, '\0'};

Now your strlen didn't work because, it finds the end of a string by searching for the '\0' terminator, which you didn't gave in your array.

It keeps on searching for '\0' (and causes access of array element out of bounds, which is an undefined behavior, and sometimes very bad). It finds it (by luck) at the 19th character hence returns that result.

Pascal Cuoq
  • 79,187
  • 7
  • 161
  • 281
0xF1
  • 6,046
  • 2
  • 27
  • 50