问题
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?
回答1:
ptr
is 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 string p
is "34EF"
. The string p+1
is "4EF"
; the string p+2
is "EF"
; p+3
is "F"
and p+4
is the empty string ""
. In this case p+4
points to the null terminator byte after the F
.
Speaking of the empty string, if the input to strtol
consists only of valid characters making up the numeric token, then ptr
should 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 *ptr
is 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!"
来源:https://stackoverflow.com/questions/10289661/strtol-second-argument