c删除动态结构中的元素

c deleting element in dynamic struct

我正在尝试删除结构中的单个元素并用最后一个元素覆盖此位置。 这是我的函数代码:

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

结构代码

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

allocateTempMemory 函数的代码:

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

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

    return 1;
}

但是,它不能正常工作。我的猜测是内存分配问题(有时会运行,有时会立即崩溃)。您知道问题出在哪里吗?谢谢

您将临时分配给 *rect,而不是释放临时。基本上你释放了*rec。以后再访问*rec会导致崩溃。

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