在介绍代码之前,先介绍一下背景:我有一个名为 math
的字符指针数组,现在,在 while
循环我试图将数学中的值转换为 int
使用atoi
并将其保存在int
中变量ai
。没有编译错误。但是,当我尝试打印 ai
时它没有打印它。不知怎的,程序运行起来没有崩溃。我不知道问题是什么,如果有问题,程序应该在 atoi
上崩溃。如果没有问题,那么它应该打印 ai
.
代码如下:
int c1 = 3; //the array contains 3 characters 1 2 3
int c2 = 0;
while(c2 < c1)
{
int ai;
ai = atoi(math[c2]);
// the array is valid, I have checked it time and again so is the content in array
write(STDOUT_FILENO,math[c2],1); //this works fine.
write(STDOUT_FILENO,&ai,sizeof(&ai));
//this doesn't print anything and somehow loop goes on to meet
//the condition.
c2++;
}
最佳答案
请记住,write
不是printf
。所以
write(STDOUT_FILENO,&ai,sizeof(&ai))
会将 sizeof(int)
个字符写入 STDOUT;如果我们假设一个 32 位 int
,它将打印 ASCII 码表中对应的字符 (ai >> 24) & ff
, (ai >> 16) & ff
、(ai >> 8) & ff
和 (ai >> 0) & ff
,这可能是四个不可打印的字符。
如果要将整数的字符串表示形式写入控制台,请使用:
printf("%d", ai);
相反。
关于c - atoi返回的值无法打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11001754/