Home > Enterprise >  why the result of strlen() out of my expection?
why the result of strlen() out of my expection?

Time:08-03

The function strlen() counts the number of characters in a string up to NUL and it doesn't contain NUL.In ASCII,NUl is equal to '\0'.

#include<stdio.h> 
#include<string.h>
int main(void)
{
    char a[]="abc";
    char b[]="abcd'\0'def";
    printf("%d\n%d",strlen(a),strlen(b));
    return 0;
}

The result is 3 and 5. THe second result is in contradiction with the first result. Thus ,I try to find how to implement strlen().

int strlen(char a[])
{
    int i;
    for(i=0;a[i]!='\0';i  );
    return i;
}

Based on this code ,I can understand the first result,but really can't understand the second one. Why is the sceond result not 4 but 5?Thanks in advance.

CodePudding user response:

You are getting 5 because you have wrapped the NUL character in single quotes, the value 5 is the length of the string "abcd`".

If you change the second example to "abcd\0ef" (no single quotes), you get a value of 4.

CodePudding user response:

char b[]="abcd'\0'def";

the array elements are

[a][b][c][d]['][0]['][d][e][f][0]

so the lenthth of the string before first [0] is 5 as it contains ' character as well.

CodePudding user response:

In ASCII, NUL is equal to '\0'.

NUL, and the null character, are equal to '\0', that is correct. But what you are looking here is a character literal (one character, \0, enclosed in single quotes). Within a string literal, those single quotes are not needed, and will indeed be interpreted as characters of their own.

So this...

char a[]="abc";
char b[]="abcd'\0'def";

...is equivalent to:

char a[]= { 'a', 'b', 'c', '\0' };
char b[]= { 'a', 'b', 'c', 'd', '\'', '\0', '\'', 'd', 'e', 'f', '\0' };

Your intention for b was this:

char b[]="abcd\0def";
  •  Tags:  
  • c
  • Related