mercredi 28 octobre 2015

how to keep using malloc?

I have a file which stored a sequence of integers. The number of total integers is unknown, so I keep using malloc() to apply new memory if i read an integer from the file. I don't know if i could keep asking for memory and add them at the end of the array. The Xcode keeps warning me that 'EXC_BAD_EXCESS' in the line of malloc(). How could i do this if i keep reading integers from a file?

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;
}

Aucun commentaire:

Enregistrer un commentaire