繁体   English   中英

谁能向我解释为什么这个atoi命令起作用以及如何工作

[英]who can please explain to me why this atoi command works and how

我用atoi命令编写了一个非常基本的c代码,然后执行它。

void
main
(void)
{
    int length;

    length = atoi("Content: 111");
    printf("atoi(\"Content: 111\") =  %d\n",length);

    length = atoi("Content:    111" + 10);
    printf("atoi(\"Content:    111\" + 10) = %d\n",length);

    length = atoi("Content: 1" + 6);
    printf("atoi(\"Content: 1\" + 6) = %d\n",length);

    length = atoi("Content: 111" + 12);
    printf("atoi(\"Content: 111\" + 12) = %d\n",length);

    length = atoi("Content-aaaaaa:            111" + 20);
    printf("atoi(\"Content-aaaaaa:            111\" + 20) = %d\n",length);

    printf("\"aaa\"+7 = %s","aaa"+7);
}

输出如下:

atoi("Content: 111") =  0
atoi("Content:    111" + 10) = 111
atoi("Content: 1" + 6) = 0
atoi("Content: 111" + 12) = 0
atoi("Content-aaaaaa:            111" + 20) = 111
"aaa"+7 = ;

这怎么可能? 为什么atoi跳过了我用+ int编写的字符数? 我应该是错误的,不是吗? 为什么最后一个printf也起作用?

我阅读了文档,没有关于此行为的任何信息:

int atoi(con​​st char * str); 将字符串转换为整数解析C字符串str,将其内容解释为整数,并将其作为int类型的值返回。

该函数首先根据需要丢弃尽可能多的空格字符(与isspace中一样),直到找到第一个非空格字符为止。 然后,从该字符开始,使用可选的初始正负号,后跟尽可能多的以10为底的数字,并将其解释为数值。

该字符串可以在形成整数的字符之后包含其他字符,这些其他字符将被忽略并且不会影响此函数的行为。

如果str中的非空格字符的第一个序列不是有效的整数,或者由于str为空或仅包含空格字符而没有这样的序列,则不执行任何转换并返回零。

atoi解析整数,但也接受前导空格字符。

其余的是简单的指针算法。

  • 当您执行"Content: 111" + 10您会将" 111"传递给atoi,它可以工作。
  • 当您执行"Content: 1" + 6您会将"t: 1传递给atoi并返回0。
  • "aaa"+7 :不要这样做:未定义的行为。

考虑示例语句

length = atoi("Content:    111" + 10);

这个表达

"Content:    111" + 10

在函数调用中用作参数的参数包含所谓的指针算法。

类型为char[16]的字符串文字"Content: 111"被隐式转换为指向第一个字符char *指针。 然后,将整数值10添加到指针,该指针产生从字符串文字开始的偏移量。

因此表达

"Content:    111" + 10
           ^

指向字符串文字中的标记位置。

您可以通过以下方式对函数调用进行成像

char *tmp = "Content:    111";
tmp = tmp + 10;
puts( tmp ); // just for testing
length = atoi( tmp );

该功能跳过前导空格字符,直到遇到数字或符号并提取数字111为止。 就这些。:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM