Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if char* p reached end of a C string?

Tags:

c++

template<class IntType>
IntType atoi_unsafe(const char* source)
{
    IntType result = IntType();
    while (source)
    {
        auto t = *source;
        result *= 10;
        result += (*source - 48);
        ++source;
    }
    return result;
}

and in main() I have:

char* number = "14256";
atoi_unsafe<unsigned>(number);

but the condition while (source) does not seem to recognize that source has iterated over the entire C string. How should it correctly check for the end of the string?

like image 238
smallB Avatar asked Nov 27 '22 18:11

smallB


1 Answers

while(source) is true until the pointer wraps around to 0, but will probably crash well before that in modern systems. You need to dereference the pointer to find a null byte, while(*source).

I hate posting short answers

like image 67
ughoavgfhw Avatar answered Nov 30 '22 06:11

ughoavgfhw