【问题标题】:c deleting element in dynamic structc删除动态结构中的元素
【发布时间】:2021-12-27 12:54:38
【问题描述】:

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

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

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

【问题讨论】:

  • allocateTempMemory 接受 struct record** temp,然后是 *temp = (struct record**)...。然后将malloc 的结果赋值给*temp 后,不测试而是测试temp

标签: c pointers struct dynamic-memory-allocation


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2018-06-10
    • 2018-06-29
    • 2018-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多