469,919 Members | 2,123 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,919 developers. It's quick & easy.

Please explain the behaviour of strlen() in the program

Hi All

Please explain why strlen returns() "16" as output here and explain the o/p for sizeof() as well

char a[3]={'a','b','c'};
printf("strlen=%d\n", strlen(a));
printf("sizeof=%d\n", sizeof(a));
printf("%d %d", strlen(a),sizeof a);


16 3

Thanks & Regards
Sathish Kumar
Jun 11 '08 #1
2 1907
9,065 Expert Mod 8TB
Try reading your C book (or looking on the web) about how C strings, strlen and the sizeof operator works.

As a little clue you did not pass a string to strlen you passed an array of characters.
Jun 11 '08 #2
As far as I know,

sizeof() operator gives the size of a certain variable or type. The fact that it is an operator means that it is applied at compile-time and not runtime.

Since you passed a 3-byte wide var, it gives 3.

On the other hand, strlen gives the length of a string. A string must be NULL terminated (i.e., it is an array of chars where its last character is NULL (which is '\0')). Since strlen cannot find a '\0' in your string, it goes reading bytes in memory (a[0], a[1], a[2], a[3]) until it finds a '\0'. In your particular case at the time you ran your program, a[16] happened to be a '\0'. So there it stopped and said 16 as the length.

You might wonder why your program is accessing a[15] if you declared it to have only a[0], a[1] and a[2]. But that's how the thing works: Welcome to C language and low-level programming.
Jun 11 '08 #3

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

12 posts views Thread by Sanjeev | last post: by
1 post views Thread by djinni | last post: by
11 posts views Thread by Sathyaish | last post: by
10 posts views Thread by sindica | last post: by
5 posts views Thread by cpptutor2000 | last post: by
5 posts views Thread by Registered User | last post: by
23 posts views Thread by gribouille | last post: by
11 posts views Thread by Pranav | last post: by
1 post views Thread by Waqarahmed | last post: by
reply views Thread by Salome Sato | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.