Search code examples
carraysstring-length

Alternative to strlen not breaking on 0


Is there any better way of getting the right length of array containing digits?

I have an array of digits: 0, 0, 1 and I try to get length of it. It obviously breaks and returns 0. I am new to C but I tried to make custom strlen function:

int custom_strlen(char *str) {
    for(int i = 1; ;i++) {
        if (str[i] == 0) {
            return i;
        }
    }
    return -47;
}

but it is not that efficient and in some cases returns unexpected values as well. The expected out put would be 3 in this case.

Is there any function to use?


Solution

  • An array of integers is not a string. C arrays do not contain length information inherently. The way strlen works is that C strings are null terminated, meaning the last character is NUL (null character), which is 0. Otherwise, there is just no way to know how long an array is.

    I think you may be wanting to do an array of '0','0','1'. Can you post the array you are using?