【问题标题】:I have troubles printing arrays of characters in C我在 C 中打印字符数组时遇到问题
【发布时间】: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 &lt; j; i++, j--),因为如果ij 不断增加,那么循环将永远不会结束。
  • OT: sprintf(buf, "%s\n") 在这里肯定是错误的。你想要printf("%s\n", buf)
  • 32位INT_MIN所需的以零结尾的字符串长度为12个字符

标签: arrays c string return


【解决方案1】:

代码至少有这些问题:

  1. 10 不足以容纳大型 int。建议至少 12 个。也许sizeof(int)*CHAR_BIT/3 + 3 进行近似概括。

  2. n = -n; 是 UB,而 n == INT_MIN

  3. 错误的增量

     //for(i = 0, j = strlen(s)-1; i < j; i++,j++){
     for(i = 0, j = strlen(s)-1; i < j; i++,j--){
    

【讨论】:

    【解决方案2】:

    是的,问题是 y++ 的东西。事实是我从带有勘误表的 K&R 版本中复制了这段代码。在书中我发现 y++ 并且我盲目地信任该函数,我在调试时从未考虑过它,假设问题是由于指针使用不当或其他原因造成的。

    当然可以改进代码。 printf es 比 sprintf 更好,我还必须使用 malloc 释放分配的内存。我还必须删除多余的未使用的包含。

    感谢您的 cmets!

    【讨论】:

      猜你喜欢
      • 2016-06-25
      • 2021-10-13
      • 1970-01-01
      • 1970-01-01
      • 2021-12-13
      • 1970-01-01
      • 2016-05-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多