简体   繁体   English

为什么以下代码会给出运行时错误 SIGSEGV

[英]Why is the following code giving runtime error SIGSEGV

I am writing the solution to a programming problem.我正在编写编程问题的解决方案。 The problem is as follows:问题如下:

Your program is to use the brute-force approach in order to find the Answer to Life, the Universe, and Everything.你的程序是使用蛮力方法来找到生命、宇宙和一切的答案。 More precisely... rewrite small numbers from input to output.更准确地说......重写从输入到输出的小数。 Stop processing input after reading in the number 42. All numbers at input are integers of one or two digits.读入数字 42 后停止处理输入。输入处的所有数字都是一位或两位整数。

I have pasted my code below.我在下面粘贴了我的代码。 I am getting segmentation fault when I submit this solution.提交此解决方案时出现分段错误。 Can someone point out what's wrong with this code?有人可以指出这段代码有什么问题吗? Any help will be much appreciated.任何帮助都感激不尽。

#include <stdio.h>

int main(void) {
    int number = 0;
    while (1)
    {
        int c = getchar();
        if (c != EOF)
        {
            number = number * 10 + c;
        }
        else
        {
            //const char value = number;
            if (number != 42)
            {
                printf(number);
                printf("\n");
                number = 0;
            }
            else
            {
                return 0;
            }
        }
    }
}

In your code在你的代码中

printf(number);

is invalid.是无效的。 You're missing the required format specifier with printf() .您缺少printf()所需的格式说明符。 You want to write你想写

printf("%d", number);

Also, printf() being a variadic function , it can accept one or more arguments and as long as that criteria is met, compilation will not fail.此外, printf()是一个可变参数函数,它可以接受一个或多个参数,只要满足该条件,编译就不会失败。 However, this instance, will cause undefined behaviour because of mismatched argument type.但是,由于参数类型不匹配,此实例将导致未定义的行为

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM