簡體   English   中英

c 刪除動態結構中的元素

[英]c deleting element in dynamic struct

我正在嘗試刪除結構中的單個元素,並用最后一個元素覆蓋這個 position。 這是我的 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;
}

結構體代碼

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

function allocateTempMemory 的代碼:

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

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

    return 1;
}

但是,它不能正常工作。 我的猜測是 memory 分配問題(有時它會運行,有時它會立即崩潰)。 你知道問題可能是什么嗎? 謝謝

您將 temp 分配給 *rect,而不是釋放 temp。 基本上你釋放了 *rec. 當您稍后訪問 *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