在C中获取调试错误

在C中获取调试错误,c,C,我是“C”的学习者,编写了一段代码,但编译后,显示了一条调试错误消息,代码如下: #include<stdio.h> void main() { int n,i=1; char c; printf("Enter Charecter:\t"); scanf("%s",&c); printf("Repeat Time\t"); scanf("%d",&n); n=n; while (i <= n)

我是“C”的学习者,编写了一段代码,但编译后,显示了一条调试错误消息,代码如下:

#include<stdio.h>
void main()
{
    int n,i=1;
    char c;
    printf("Enter Charecter:\t");
    scanf("%s",&c);
    printf("Repeat Time\t");
    scanf("%d",&n);
    n=n;
    while (i <= n)
    {
        printf("%c",c);
        i++;
    }
}
#包括
void main()
{
int n,i=1;
字符c;
printf(“输入字符:\t”);
scanf(“%s”、&c);
printf(“重复时间\t”);
scanf(“%d”和“&n”);
n=n;
而(i
scanf(“%s”和&c);
应该是
scanf(“%c”和&c);

%s
格式说明符告诉
scanf
您正在传递一个字符数组。您正在传递一个字符,因此需要使用
%c

当前代码的行为将不可预测,因为
scanf
将尝试向您提供的地址写入一个任意长的字,后跟nul终止符。此地址为单个字符分配了内存(在堆栈上),因此您最终会过度写入可供程序其他部分使用的内存(比如其他局部变量)。

scanf(“%s”,&c)
正在写入内存,它不应该像
c
是单个
char
那样写入,但是
%s
希望它的参数是数组。当
scanf()
附加一个空字符时,它至少会向
c
写入两个
char
(从
stdin
读取的
char
加上空终止符),这太多了

使用
char[]
并限制
scanf()写入的
char
的数量:

并使用
printf(“%s”,data);
代替
%c
,或使用
%c”
作为
scanf()中的格式说明符

始终检查的返回值,即成功分配的数量,以确保后续代码不会处理过时或未初始化的变量:

if (1 == scanf("%d", &n))
{
    /* 'n' assigned. 'n = n;' is unrequired. */
}

这是您的代码的工作版本。有关修复,请参阅代码中的内联注释:

#include<stdio.h>
void main()
{
    int n,i=1;
    char c;
    printf("Enter Character:\t");
    scanf("%c",&c);//Use %c instead of %s
    printf("Repeat Time\t");
    scanf("%d",&n);
    n=n;//SUGGESTION:This line is not necessary. When you do scanf on 'n' you store the value in 'n'
    while (i <= n)//COMMENT:Appears you want to print the same character n times?
    {
        printf("%c",c);
        i++;
    }
    return;//Just a good practice
}
#包括
void main()
{
int n,i=1;
字符c;
printf(“输入字符:\t”);
scanf(“%c”,&c);//使用%c而不是%s
printf(“重复时间\t”);
scanf(“%d”和“&n”);
n=n;//建议:这一行不是必需的。当对“n”执行scanf时,将值存储在“n”中

虽然(我我不确定你是否理解你另一个问题的答案:

它们分别用于特定的作业

如果您想获得一个:

  • stdin
    中的字符使用
    %c

  • 字符串(一组字符)使用
    %s

  • 整数使用
    %d
此代码:

char c;
printf("Enter Character:\t");
scanf("%c",&c);
将从
stdin
中读取1个字符,并在其中留下一个换行(
'\n'
)字符。假设用户在
stdin
缓冲区中输入字母
a

A\n
scanf()
将拉出
'A'
并将其存储在
char c
中,并保留换行符。接下来,它将要求输入int,用户可能输入
5
stdin
现在有:

\n5
scanf()
将取
5
并将其置于
int n
中。如果您想使用该'\n',有许多选项,其中一个选项是:

char c;
printf("Enter Character:\t");
scanf("%c",&c);  // This gets the 'A' and stores it in c
getchar();       // This gets the \n and trashes it

您可以向我们显示实际的错误消息吗?
n=n;
--这是为了做什么?您的
main
-功能与不兼容standard@Almo下面是屏幕截图1)void main是一种非常糟糕的做法。2)如果I/O被缓冲(很可能会是这样),那么在扫描完成后,您将看不到printf的输出3)n=n的赋值完全没有意义。是的,我想把同一个字符打印n次……谢谢,这很有意义:)@汤姆·坦纳:1)同意。gcc通常不允许这样的代码。但是,由于它不知道OP使用的是哪一个编译器,所以最好保持代码完整。2)取决于缓冲机制。但是,代码是有效的C,并且肯定会按预期工作。3)我建议OP在注释中作为内联注释。感谢这些概念帮助我们理解t:)@JessicaLingmn-很乐意帮忙,这个新线人物似乎让很多人都绊倒了
char c;
printf("Enter Character:\t");
scanf("%c",&c);  // This gets the 'A' and stores it in c
getchar();       // This gets the \n and trashes it