How does the second argument of strtol work?
Here is what I tried:
strtol(str, &ptr, 10)
where ptr is a char * and str is a string. Now, If I pass in str as '34EF', and print *ptr, it correctly gives me E, and *(ptr+1) gives me F, however if I print ptr, it gives me EF! Shouldn’t printing ptr just result in a rubbish value like a hex address or something?
ptris a pointer to the interior of a null terminated string. So given"34EF"it ends up pointing to the character'E'and the string starting at that address is"EF".A four-character C string like
p = "34EF"actually contains five strings in one. The stringpis"34EF". The stringp+1is"4EF"; the stringp+2is"EF";p+3is"F"andp+4is the empty string"". In this casep+4points to the null terminator byte after theF.Speaking of the empty string, if the input to
strtolconsists only of valid characters making up the numeric token, thenptrshould point to an empty string.If you want to disallow trailing junk, you can test for this. That is, even if a valid number parses out, if
*ptris not 0, then the input has trailing junk. In some cases, it is good to reject that: “Dear user, 10Zdf is not a number; please enter a number!”