Aleksey Bichuk
Aleksey Bichuk

Reputation: 26

Memory in C (array structures)

i have dynamic array of structures.

struct Pacient
{
    char name[30];
    char surname[30];
    char middleName[30];
    char nationality[30];
    float height;
    float weight;
    char phone[30];
    struct Date  {
        int day;
        int month;
        int year;
    }dateOfBirth;
    struct Adress {
        char city[30];
        char street[30];
        int numberOfHouse;
    } adress;
    struct Hospital {
        int numberOfHospital;
        char nameOfOffice[30];
        int numberOfMedicalCart;
        char groupOfBlood[10];
        char nameOfDiagnosis[30];
    }hospitalInfo;
};

Me need add,delete element from array.

Pacient* pacients;
pacients = (Pacient*)calloc(count, sizeof(Pacient));

^ my declaration of array, count - size of array.

I made func addNewPacient and deleteLastElement.

 void addNewPacient() {
    count++;
    pacients = (Pacient*)realloc(pacients, sizeof(Pacient)*count );
    ......//many scanf...
}
void removeLastElement() {
    count--;
    pacients = (Pacient*)realloc(pacients, count * sizeof(Pacient*));
}

For start, i input info about (example) 3 users. Ivan, Petro and Grisha. I call method printAll() and all be fine. {Ivan ....., Peto ...., Grisha ....}

After i can call method addNewPacient() (Nazar) and all will be fine again. {Ivan ....., Peto ...., Grisha ...., Nazar....} But when i remove last element from array, all almost will be fine ALMOST. {Ivan ......, Petro ....., Grisdksaldaskfpwqe###221 ......} Penult element distorted. I think i have problem with deleteLastElement(), help plz)

Upvotes: 0

Views: 74

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140188

you're right: your list shrink code has a problem:

pacients = (Pacient*)realloc(pacients, count * sizeof(Pacient*));

you're passing the size of the pointer not of the structure. You did well for growth function. Pass the actual size of the structure or you'll have a lot less memory to work with, which explains the trashed end elements.

Now that I pointed that out, the fix is easy: just copy the line above (should have done that in the first place or done a macro to avoid copying/pasting):

pacients = realloc(pacients, count * sizeof(Pacient));

Upvotes: 2

Related Questions