c在使用 itoa() 函数后 printf() 调用的奇怪行为

  • 本文关键字:调用 printf 函数 itoa
  • 更新时间 :
  • 英文 :


我正在复习我的C技能。我尝试了以下代码来学习itoa()函数的用法:

#include<stdio.h>
#include<stdlib.h>
void main(){
    int x = 9;
    char str[] = "ankush";
    char c[] = "";
    printf("%s printed on line  %dn",str,__LINE__);
    itoa(x,c,10);
    printf(c);
    printf("n %s n",str); //this statement is printing nothing
    printf("the current line is %d",__LINE__);
}

我得到了以下输出:

ankush printed on line 10
9
                      //here nothing is printed
the current line is 14

问题是,如果我从代码中itoa(x,c,10);注释语句,我会打印上述语句并获得以下输出:

ankush printed on 10 line
 ankush   //so i got it printed
the current line is 14

这是itoa()的行为还是我做错了什么。问候。

正如人们在评论中指出的那样,变量 c 表示的数组的大小为 1。由于 C 要求字符串具有 NULL 终止符,因此只能在 c 中存储长度为 0 的字符串。但是,当您调用 itoa 时,它不知道您交给它的缓冲区只有 1 个字符长,因此它会很高兴地在c后继续将数字写入内存(这很可能是包含 str 的内存)。

若要解决此问题,请将 c 声明为足够大的大小来处理您计划放入其中的字符串,加上 NULL 终止符的 1。32 位int可以容纳的最大值为 10 位,因此您可以使用 char c[11]

为了进一步解释上面的内存覆盖情况,让我们考虑cstr被分配到堆栈上的连续区域中(因为它们是局部变量)。因此,c可能会占用内存地址 1000(因为它是零字符串加上 NULL 终止符),而str将占用内存地址 1001 到 1008(因为它有 6 个字符,加上 NULL 终止符)。当你尝试将字符串"9"写入c时,数字9被放入内存地址1000,NULL 终止符被放入内存地址1001。由于 1001 是 str 的第一个地址,str现在表示一个零长度字符串(NULL 终止符在任何其他字符之前)。这就是为什么你会得到空白。

c 必须是一个足够长的缓冲区来容纳你的数字。

char c[20] ;

而不是

char c[] = "";

最新更新