微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么putchar用此简单代码编写新行?

如何解决为什么putchar用此简单代码编写新行?

我不明白为什么我在运行此程序时将过多的空白写入stdout。

$ valgrind ./bin/speller texts/lalaland.txt > test/lalaland.txt
==28984== Memcheck,a memory error detector
==28984== copyright (C) 2002-2017,and GNU GPL'd,by Julian Seward et al.
==28984== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==28984== Command: ./bin/speller texts/lalaland.txt
==28984==
==28984==
==28984== HEAP SUMMARY:
==28984==     in use at exit: 0 bytes in 0 blocks
==28984==   total heap usage: 143,095 allocs,143,095 frees,8,022,392 bytes allocated
==28984==
==28984== All heap blocks were freed -- no leaks are possible
==28984==
==28984== For counts of detected and suppressed errors,rerun with: -v
==28984== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

输出

lalaland.txt

解决方法

您的内循环条件是错误的,导致您超出范围。它始终受第一个参数strlen(*argv)的限制(由于使用了较早的argv++),即使处理第二个及后续参数也是如此。由于您读出的长度为"hello",因此您过度读取了"baby",而无法读取所有的"yoyoyo"。用一个字符过度读baby最终会向NUL写一个stdout,我猜您的终端正在以类似于换行的方式进行解释。

我建议:

  1. 解决该问题,以便您使用每个参数的长度来打印它,并且
  2. 用简单的数组索引语法替换难以理解的指针算法

最终结果如下:

int main(int argc,char **argv)
{
    for (int i = 1; i < argc; i++)  // Adjust bounds to loop over provided args without mucking with argv directly
    {
        for (int j = 0; j < strlen(argv[i]); j++)  // Loop to length of current arg
        {
            putchar(argv[i][j]);
        }
        printf("\n");
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。