【问题标题】:Why is this exception thrown in the visual studio C compiler?为什么在 Visual Studio C 编译器中会引发此异常?
【发布时间】:2010-03-21 04:16:31
【问题描述】:

我正在努力提高我的 C 编程能力,并尝试在获取字符的循环内部测试从输入流中显示一个字符。我正在使用getchar 方法。

当我的代码中出现 printf 语句时,我收到了一个异常。 (如果我注释掉该函数中的printf 行,则不会抛出异常)。

异常:未处理的异常 0x611c91ad (msvcr90d.dll) 在 firstOS.exe: 0xC0000005: 访问 违规读取位置0x00002573。

这是代码...有什么想法吗?谢谢。

PS。我正在使用stdio.h 库。

/*getCommandPromptNew - obtains a string command prompt.*/
void getCommandPromptNew(char s[], int lim){    

    int i, c;

    for(i=0; i < lim-1 && (c=getchar())!=EOF && c!='\n'; ++i){
        s[i] = c;
        printf('%s', c);
    }

}

【问题讨论】:

    标签: c visual-studio exception printf getchar


    【解决方案1】:

    尝试改变:

    printf('%s', c);
    

    printf("%c", c);
    

    如果您希望在循环的 end 处打印整个字符串,您需要使用 NULL 字符来终止它:

    s[i] = 0;
    

    然后您可以将其打印为:

    printf("%s", s);
    

    【讨论】:

      【解决方案2】:

      您应该检查的第一件事是:您是否为 s[] 分配了内存。
      第二:printf("%c", c); // 我可以假设 %s - 正在等待以空字符结尾的字符串。
      第三: printf() 中的 "" vs '' 可能有问题。

      【讨论】:

      • 也感谢您的意见。
      猜你喜欢
      • 1970-01-01
      • 2019-11-23
      • 1970-01-01
      • 1970-01-01
      • 2011-04-21
      • 1970-01-01
      • 2020-03-21
      • 2010-12-18
      • 1970-01-01
      相关资源
      最近更新 更多