Question

Hello I for an exercise at University i need to malloc an array with this way. The array at stars has 1 slot. If the inputs are more than one then the array is doubled. If the inputs are more than 2 then it is doubled again etc. After this I have to crop the array to fit to the number of inputs. For example if I have 5 inputs then the array will have 8 slots and I must make it to have 5 slots which I cannot figure out how. Here is my code so far:

nameInfoT* ReadNames(int* size){
    nameInfoT* names ;
    int array_size=1;
    int entries=0;
    char input[length];
    names=(nameInfoT*) malloc(sizeof(nameInfoT)*array_size);

    do{
        scanf("%s",input);
        if(!strcmp(input,"END")) break;

        if(entries==array_size){
            array_size=array_size*2;
            names= (nameInfoT*) realloc(names,sizeof(nameInfoT)*array_size);
        }

        names[entries].name=(char*)malloc(sizeof(char)*strlen(input));
        strcpy(names[entries].name,input);

        entries++;

    }while(1);

    printf("there are %d free spaces \n",array_size-entries);
    *size=entries;
    printf("there are %d entries \n",*size);

    int i;
    for(i=array_size;i>entries;i--){
        free(names[i]);//here it won't compile 
    }
    return names;

}
Était-ce utile?

La solution

You can only free the result of malloc/calloc/realloc. You cannot free individual elements. So in the end you can simply realloc again to the desired final size.

Autres conseils

You have a couple of other problems:
1) when you allocate space for the input string, you need to add 1 to keep the trailing '\0'
2) before your realloc, you should have a switch statement which will take the array_size and use that to determine the new size. If I understand your problem, you want to go from 1 -> 2 -> 4 -> n (where n is the next number). Your realloc code just doubles each time. You need to change that.
3) when you free the entries, you need to be careful since you don't seem to be freeing the 'name' member of the class/struct.
4) after freeing the members in the loop, then do one free on the names class/struct.

I could look into it more carefully later.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top