Segmentation fault (core dumped) when using fscanf to read into a pointer

后端 未结 2 2007
自闭症患者
自闭症患者 2021-01-29 11:24

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:



        
2条回答
  •  渐次进展
    2021-01-29 11:59

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

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

    Here is one way to fix it:

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

    Here is another way to fix it:

    int b;
    int *a = &b;
    

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


    Change this:

    int *a;
    

    To this:

    int a;
    

    And this:

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

    To this:

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

提交回复
热议问题