【发布时间】:2021-02-08 11:36:52
【问题描述】:
问题是下面的代码什么也没打印。我非常努力,使用不同的方法,我使用固定大小的数组,我尝试从 void 函数打印数组,我尝试 printf 和 sprintf,我尝试使用静态 s 变量,我尝试循环数组并打印字符结果始终相同,0 个错误,0 个警告,并且从不打印结果。大约 30 秒后,程序自动终止,输出如下:
将 56 转换为 ascii: 进程返回 -1073741819 (0xC0000005) 执行时间:4.763 s 按任意键继续。
这是代码(我可能使用了太多包含,但这是因为我尝试了所有方法):
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void reverse(char s[])
{
int c, i, j;
for(i = 0, j = strlen(s)-1; i < j; i++,j++){
c = s[i];
s[i] = s[j];
s[j] = c;
}
}
char * itoascii(int n)
{ char *s = malloc(10);
/*if(s == NULL)
return NULL;*/
int i, sign;
if((sign = n) < 0)
n = -n; // if n is negative, make it positive. And store the sign into sign
i = 0;
do {
s[i++] = n % 10 + '0'; // turn a digit into a string and then increment i
}while(( n /= 10) > 0);
if(sign < 0)
s[i++] = '-';
s[i] = '\0';
reverse(s);
return s;
}
int main()
{ int n;
n = 56;
printf("Convert %d to ascii:\n", n);
char *buf = itoascii(n);
sprintf(buf, "%s\n");
return 0;
}
【问题讨论】:
-
sprintf in 用于打印成字符串,如果要打印出字符串,请尝试
printf("%s\n", buf); -
在循环增量中,
j++应该是j--。否则它会从你的数组末端走出来。 -
我猜你的意思是
for (i = 0, j = strlen(s) - 1; i < j; i++, j--),因为如果i和j不断增加,那么循环将永远不会结束。 -
OT:
sprintf(buf, "%s\n")在这里肯定是错误的。你想要printf("%s\n", buf)。 -
32位
INT_MIN所需的以零结尾的字符串长度为12个字符