*str 和 atoi(str) 之间的区别
我进行了标记化,并在文本文件(已被读入数组“store”中)上使用了带有分隔符“=”的 strtok,
因此文件中有一条语句:TCP.port = 180
我做到了:
str = strtok(store, "=");
str= strtok(NULL, "=");
现在如果我执行*str
,它会给我'82'(可能是一些垃圾值) 但是atoi(str);给了我180(正确的值)
我希望有人能阐明这一点,取消引用str不应该也给我180吗?
I was tokenizing, and used strtok on a text file (which has been read into an array 'store') with the delimiter '='
so there was a statement in the file : TCP.port = 180
And I did:
str = strtok(store, "=");
str= strtok(NULL, "=");
Now if I do *str
, it gives me '82' (probably some junk value)
but atoi(str);
gives me 180 (the correct value)
I was hoping someone could shed light onto this, shouldn't dereferencing str give me 180 too?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
编译并运行该程序。它应该能让您更好地了解正在发生的事情。
这是输出:
Compile and run this program. It should give you a better idea of what's going on.
Here's the output:
不。
atoi
为您提供由str
指向的字符串表示的整数。取消引用str
(*str) 会得到 charstr
指向的值(这不是您编写的值)。No.
atoi
gives you the integer represented by the stringstr
points to. Dereferencingstr
(*str) gives you the value of the charstr
points to (which is not the value you wrote).您需要准确了解字符串在 C 中的工作原理才能了解这里发生的情况。
str
变量是指向字符串中第一个字符的指针。解引用str
给出str
指向的值,即字符'1'
。同样,取消引用str+1
将给出下一个字符'8'
。您可以看到如何用*(str+3)
(或者等效的str[3]
)表示字符串的结尾,它给出一个空字节。函数 atoi 知道如何将字符解释为以 10 为基数的 ASCII 字符字符串,这比取消引用要复杂得多。You need to understand exactly how strings work in C to see what's going on here. The
str
variable is a pointer to the first character in the string. Dereferencingstr
gives the value pointed to bystr
, namely the character'1'
. Similarly, dereferencingstr+1
will give you the next character,'8'
. You can see how the end of the string is signified with*(str+3)
(or, equivalently,str[3]
), which gives a null byte. The functionatoi
knows how to interpret the characters as a base-10 string of ASCII characters, which is much more complicated than a dereference.