Home > Blockchain >  The length of a char array
The length of a char array

Time:10-16

Can anyone explain why strlen returned 1 knowing that ptr1's size is 4 ?

int main()
{
    char ptr1[4];
    printf("%lu", strlen(ptr1));
}

Result is : 1

CodePudding user response:

strlen() returns number of characters till reaching to \0 (exluding \0).

and also, the initial value of char[] is not deterministic and we cant be sure about it.

in your case, your array has the capacity of four but it might be initialize with something like {'a','\0', ... } so strlen() returned 1.

CodePudding user response:

The size of an array is only available within the same lexical context using the sizeof operator.

Example:

int main()
{
    char ptr1[4];
    printf("%lu", sizeof(ptr1));
}

This also works for variable length arrays, but not for array parameters to functions, as those are really pointers, so be careful.

strlen on the other hand computes the length of a C string by searching for the terminating NUL byte, not really useful for non-string arrays. Also, because the array has an undefined value, calling strlen on it will cause undefined behavior, even with strings you need to make extra sure the string is terminated, or alternatively, use strnlen (POSIX) or memchr (C89).

  • Related