*str 和 atoi(str) 之间的区别

发布于 2024-11-29 01:09:52 字数 312 浏览 1 评论 0原文

我进行了标记化,并在文本文件(已被读入数组“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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

属性 2024-12-06 01:09:52

编译并运行该程序。它应该能让您更好地了解正在发生的事情。

#include <stdlib.h>
#include <stdio.h>

int main(void) {
    const char *s = "180";
    printf("s       = \"%s\"\n", s);
    printf("atoi(s) = %d\n", atoi(s));
    printf("*s      = %d = '%c'\n", *s, *s);
    return 0;
}

这是输出:

s       = "180"
atoi(s) = 180
*s      = 49 = '1'

Compile and run this program. It should give you a better idea of what's going on.

#include <stdlib.h>
#include <stdio.h>

int main(void) {
    const char *s = "180";
    printf("s       = \"%s\"\n", s);
    printf("atoi(s) = %d\n", atoi(s));
    printf("*s      = %d = '%c'\n", *s, *s);
    return 0;
}

Here's the output:

s       = "180"
atoi(s) = 180
*s      = 49 = '1'
仅此而已 2024-12-06 01:09:52

不。atoi 为您提供由 str 指向的字符串表示的整数。取消引用 str (*str) 会得到 char str 指向的值(这不是您编写的值)。

No. atoi gives you the integer represented by the string str points to. Dereferencing str (*str) gives you the value of the char str points to (which is not the value you wrote).

三五鸿雁 2024-12-06 01:09:52

您需要准确了解字符串在 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. Dereferencing str gives the value pointed to by str, namely the character '1'. Similarly, dereferencing str+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 function atoi knows how to interpret the characters as a base-10 string of ASCII characters, which is much more complicated than a dereference.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文