Strtol第二个论点 [英] Strtol second argument
问题描述
strtol
的第二个参数如何工作?
How does the second argument of strtol
work?
这是我尝试过的:
strtol(str, &ptr, 10)
其中,ptr
是char *
,str
是字符串.现在,如果我以'34EF'
的形式输入str
并打印*ptr
,它正确地给了我E
,而*(ptr+1)
给了我F
,但是,如果我打印了ptr
,它给了我EF!
不应该打印ptr
只是产生一个垃圾值,例如十六进制地址之类的东西吗?
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?
推荐答案
ptr
是指向以null结尾的字符串内部的指针.因此,给定"34EF"
,它最终指向字符'E'
,并且从该地址开始的字符串为"EF"
.
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"
.
像p = "34EF"
这样的四字符C字符串实际上包含五个字符串.字符串p
是"34EF"
.字符串p+1
是"4EF"
;字符串p+2
是"EF"
; p+3
是"F"
,p+4
是空字符串""
.在这种情况下,p+4
指向F
之后的空终止符字节.
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
.
说到空字符串,如果strtol
的输入仅由组成数字标记的有效字符组成,则ptr
应该指向一个空字符串.
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.
如果您想禁止尾随垃圾,可以对此进行测试.也就是说,即使解析出一个有效的数字,如果*ptr
不为0,那么输入也将具有结尾垃圾.在某些情况下,最好拒绝以下情况:亲爱的用户,10Zdf不是数字;请输入数字!"
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!"
这篇关于Strtol第二个论点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!