According to this document,
The second argument (char **endptr) seems to be a waste of space! If it is set to NULL, STRTOL seems to work its way down the string until it finds an invalid character and then stops. All valid chars read are then converted if the string starts with an invalid character the function returns ZERO (0).
It means that the following code should detect 2
as the hex number:
int main()
{
char * string = "p1pp2ppp";
unsigned integer = strtoul(string, NULL, 16);
printf("%u", integer);
return 0;
}
but, it is returning zero.
Why?
The man page says the following about the second argument:
For example:
Output:
We can see that when
strtol
returnsp
points to the first character instr
that cannot be converted. This can be used to parse through the string a bit at a time, or to see if the entire string can be converted or if there are some extra characters.In the case of your example, the first character in
string
, namely "p" is not a base 10 digit so nothing gets converted and the function returns 0.