我試圖洗掉結構中的單個元素并用最后一個覆寫這個位置。這是我的函式代碼:
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;
}
但是,它不能正常作業。我的猜測是記憶體分配問題(有時它會運行,有時它會立即崩潰)。你知道可能是什么問題嗎?謝謝
uj5u.com熱心網友回復:
您將 temp 分配給 *rect,而不是您的 free temp。基本上你釋放了*rec。當您稍后訪問 *rec 時,它會導致崩潰。
*rec = temp;
....
free(temp); // cause *rec freed. Should not be freed.
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/395874.html
上一篇:是否可以更改常量資料值?
