fscanf()期间的分段错误?

时间:2017-03-28 00:00:01

标签: c segmentation-fault scanf

这是我在动态内存分配,指针和文件方面学到的初学程序实验。每次编译我都会遇到分段错误。我无法修复fscanf()期间发生的错误。

#include <stdio.h>
#include <stdlib.h>
// create int aboveavg();

double average(int *ptr, int size){
        int count = 0;
        double sum = 0;
        while(count <= size){
                sum += *ptr;
                ptr++;
                count++;
        }
        sum /= size;
        return sum;
}
int main(){
        int n = 10;
        int *ptr = (int*)calloc(n, sizeof(int)); //allocate dynamic memory
        printf("Allocated %d integers\n", n);
        FILE *input = fopen("a.txt" , "r");      //open file
        if(input = NULL){                        //error check
                printf("Error! memory not allocated.");
                exit(0);
        }
        int count = 0, i=0;
        printf("check point\n");
        while(fscanf(input, "%d", &ptr[i]) == 1){  //**Segmentation Fault**
                if(count == n){
                        n *=2;
                        ptr = (int*)realloc(ptr,n* sizeof(int));
                        printf("Reallocated to %d integers\n", n);
                }
                i++;
                count++;
        }
        fclose(input);
        double avg = average(ptr, n);
        printf("average of %f\n", avg);
        free(ptr);
        printf("Dynamic array freed\n");
        return 0;
}

搜索答案(google或堆栈溢出),对我没什么帮助。任何人都可以暗示/指出我做错了什么。

0 个答案:

没有答案