简体   繁体   English

c 删除动态结构中的元素

[英]c deleting element in dynamic struct

i'm trying to delete a single element in the struct and override this position with the last one.我正在尝试删除结构中的单个元素,并用最后一个元素覆盖这个 position。 Here is my code of a function:这是我的 function 代码:

int deleteElement(struct record **rec, int *length, int elementToDelete){
    struct record *temp = NULL;

    allocateTempMemory(&temp, ((*length) - 1));

    for (int i = 0; i < ((*length) - 1); i++){
        if (elementToDelete != i){
            temp[i] = (*rec)[i];
            temp[i].ID = (*rec)[i].ID;
            temp[i].Salary = (*rec)[i].Salary;
            strcpy(temp[i].Name, (*rec)[i].Name);
        } else {temp[i] = (*rec)[(*length) - 1]; 
                temp[i].ID = (*rec)[(*length) - 1].ID;
                temp[i].Salary = (*rec)[(*length) - 1].Salary;
                strcpy(temp[i].Name, (*rec)[(*length) - 1].Name);
                };
    }
    
    free(*rec);
    *rec = temp;
    
     for (int i = 0; i < ((*length) - 1); i++){
        (*rec)[i] = temp[i];
        (*rec)[i].ID = temp[i].ID;
        (*rec)[i].Salary = temp[i].Salary;
        strcpy((*rec)[i].Name, temp[i].Name);
    }

    (*length)--;


    free(temp);

    return 1;
}

code of the struct结构体代码

struct record{
    char Name[100];
    double Salary;
    int ID;
};

code of the function allocateTempMemory: function allocateTempMemory 的代码:

int allocateTempMemory(struct record **temp, int length){
    *temp = (struct record **)malloc(sizeof(struct record) * length);

    if (temp == NULL){
        return 0;
    }

    return 1;
}

However, it does not work properly.但是,它不能正常工作。 My guess are memory allocation issues (sometimes it runs through and sometimes it crashes immediately).我的猜测是 memory 分配问题(有时它会运行,有时它会立即崩溃)。 Do you have any idea what the problem may be?你知道问题可能是什么吗? thanks谢谢

You assign temp to *rect, than you free temp.您将 temp 分配给 *rect,而不是释放 temp。 basically you freed *rec.基本上你释放了 *rec. When you access *rec later it will cause crash.当您稍后访问 *rec 时,它将导致崩溃。

*rec = temp;
....
free(temp); // cause *rec freed. Should not be freed.

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

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