cstrncmp

Determine which char * is the shortest without strlen


I have two different char *, char *string1 which is constant and char *string2 which can change. I retrieve char *string2 from a list.

I want to find the length of the shortest char * to use it in:

strncmp(string1, string2, shortest);.

This will be in a while-loop like below:

...
int shortest;
while (string2) {
    // get the length of the shortest char *
    if (!strncmp(string1, string2, shortest))
        break;    
    string2 = list_next(list); // Returns NULL if there is no elements left
}
...

I can't use strlen(const char *s) because it's too slow for my usecase.


Solution

  • Create a struct that contains the pointer and the length. Then you have the length precalculated and checking it should be fast.

    An even better idea is to use someone else's string library that already does this for you. Besides calculating string length most of the libraries vastly improve C's buffer security by avoiding the standard string operations.