By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
449,017 Members | 1,093 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 449,017 IT Pros & Developers. It's quick & easy.

Please explain the behaviour of strlen() in the program

P: 34
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
Share this Question
Share on Google+
2 Replies

Expert Mod 5K+
P: 8,916
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

P: 86
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.