使用fscanf读入指针时出现分段错误(内核已转储) [英] Segmentation fault (core dumped) when using fscanf to read into a pointer

查看:530
本文介绍了使用fscanf读入指针时出现分段错误(内核已转储)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用fscanf读取和打印屏幕上的每个字符,但是在运行程序时遇到了段错误(核心已转储).这是我的代码:

I'm trying to use fscanf to read and print every character on the screen, but I'm getting a segmentation fault (core dumped) when I run the program. Here's my code:

#include <stdio.h>

main(int argc, char * argv[]) {
    int *a ;
    FILE *input;

    if (argc>=2) {
        input= fopen(argv[1],"r");

        if (input!=NULL) {
            while (feof(input)==0) {
                fscanf(input,"%d\n",a);
                printf("%d\n",*a);
            }
            fclose(input);
        } else {
            printf("Error!\n");
        }
    }
}

我将文件作为参数提供,像这样:

I provide the file as an argument, like this:

./myprog input.txt

文件input.txt包含以下内容:

23
47
55
70

推荐答案

变量a未初始化为指向有效的内存地址.

Variable a is not initialized to point to a valid memory address.

因此,它很可能指向无效的内存地址.

Therefore, it is most likely pointing to an invalid memory address.

这是一种解决方法:

int *a = malloc(sizeof(int));
...
free(a); // when done using it

这是另一种解决方法:

int b;
int *a = &b;

但是我建议您按照以下步骤操作,以使其更简单,更干净...

But I suggest that you follow the steps below in order to make it simpler and cleaner...

更改此内容:

int *a;

为此:

int a;

这是

fscanf(input,"%d\n",a);

为此:

fscanf(input,"%d\n",&a);

这篇关于使用fscanf读入指针时出现分段错误(内核已转储)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆