我有一个存储整数序列的文件。整数总数未知,因此如果从文件中读取整数,我将继续使用malloc()来应用新内存。
我不知道我是否可以继续请求内存并将它们添加到数组的末尾。Xcode一直警告我malloc()行中的“EXC_BAD_EXCESS”。
如果我一直从文件中读取整数,我怎么能这样做呢?

int main()
{
    //1.read from file
    int *a = NULL;
    int size=0;
    //char ch;
    FILE *in;

    //open file
    if ( (in=fopen("/Users/NUO/Desktop/in.text","r")) == NULL){
        printf("cannot open input file\n");
        exit(0);    //if file open fail, stop the program
    }

    while( ! feof(in) ){
        a = (int *)malloc(sizeof(int));
        fscanf(in,"%d", &a[size] );;
        printf("a[i]=%d\n",a[size]);
        size++;
    }
fclose(in);
return 0;
}

最佳答案

不要使用malloc,而是使用realloc
不要在feof(in)循环中使用whileSee why

int number;
while( fscanf(in, "%d", &number) == 1 ){
    a = realloc(a, sizeof(int)*(size+1));
    if ( a == NULL )
    {
       // Problem.
       exit(0);
    }
    a[size] = number;
    printf("a[i]=%d\n", a[size]);
    size++;
}

关于c - 如何继续使用malloc?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33401727/

10-08 22:15
查看更多