freeboy1015
freeboy1015

Reputation: 2337

Why the result is 0?

See these code as below:

#include<stdio.h>
#include<stdlib.h>

int main()
{
 char a[1000];
 int i;
 for(i = 1;i<1000;i++)
 {
  a[i] = 5;
 }

 printf("%d\n",strlen(a));

 return 0;
}

the result is 0 , why? Any explanation will be appreciated.

Upvotes: 1

Views: 290

Answers (3)

Viku
Viku

Reputation: 2973

 #include<stdio.h>
 #include<stdlib.h>
 int main()
 {
     char a[1000];
     int i;
     for(i = 0;i<1000;i++)//starts with 0 not 1
       a[i] = 5;
     a[i] = '\0';//NULL terminator shall be there 
     printf("%d\n",strlen(a));//1000

     return 0;
 }

Upvotes: -1

prady00
prady00

Reputation: 741

strlen() starts counting from 0 not 1. Do this and you will be going:

for(i = 0;i<1000;i++)

Upvotes: 1

Qaz
Qaz

Reputation: 61920

You never assign or intialize a[0]. In this case, it just happened to be '\0', so strlen(a) returns 0.

It's worth noting that calling strlen on a here is undefined behaviour, as you're indirectly trying to read that uninitialized, garbage memory that is a[0] as the first step on the search to find a null terminator. Even setting that to 0 explicitly would still cause problems with it running off of the end of the array until it finds a 0, crashes, or blows up.

Upvotes: 15

Related Questions