简体   繁体   English

C语言中的内存(数组结构)

[英]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. 我做了func addNewPacient和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. 首先,我输入有关(示例)3个用户的信息。 Ivan, Petro and Grisha. 伊万(Ivan),彼得罗(Petro)和格里沙(Grisha)。 I call method printAll() and all be fine. 我调用方法printAll(),一切都很好。 {Ivan ....., Peto ...., Grisha ....} {伊万(Ivan),佩托(Peto),格里莎(Grisha)。

After i can call method addNewPacient() (Nazar) and all will be fine again. 在我可以调用方法addNewPacient()(Nazar)之后,一切都会好起来的。 {Ivan ....., Peto ...., Grisha ...., Nazar....} But when i remove last element from array, all almost will be fine ALMOST. {Ivan .....,Peto ....,Grisha ....,Nazar ....}但是,当我从数组中删除最后一个元素时,几乎一切都会好起来的。 {Ivan ......, Petro ....., Grisdksaldaskfpwqe###221 ......} Penult element distorted. {Ivan ......,Petro .....,Grisdksaldaskfpwqe ### 221 ......} Penult元素变形。 I think i have problem with deleteLastElement(), help plz) 我认为我对deleteLastElement()有问题,请帮助

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM