【发布时间】: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