Strtol second argument

柔情痞子 提交于 2019-12-25 08:36:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!