【发布时间】:2015-05-07 23:10:27
【问题描述】:
我是新的 c 程序员。我正在开发一个小型学生数据库。该数据库由结构student组成。每个学生都有一个名字、姓氏和入学编号。一种方法是删除具有入学编号的学生。所以我在动态数组中搜索了预科数。然后我尝试将要删除的元素之前的元素和要删除的元素之后的元素复制到另一个动态数组中。第一个问题是复制过程。它不起作用,虽然我使用 memcpy。当我有三个元素并删除一个元素时,我发现 2 个没有信息的结构。我的意思是 temp 中的 2 个空结构不包含任何信息(例如姓氏......)。我不知道为什么 memcpy 不起作用。 第二个问题在于当我尝试释放动态内存时出现分段错误。我正在做的是将新结构复制到 temp 之后。我释放数据库。然后我设置db = temp。所以通常 db 指向新的动态数组。但我也得到分段错误这是代码:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
typedef int bool;
#define true 1
#define false 0
struct student{
char lastname[20];
char firstname[20];
int mNr;
char courseOfStudy[20];
char nationality[20];
};
struct student * db;
struct student * ptrDb;
int size=0;
void createDb(int s){
size=s;
db= (struct student *)malloc(100*sizeof(struct student *));
ptrDb=db;
printf("database was created\n");
}
struct student getData(char lastname [], char firstname[], int matNr, char courseOfStudy [], char nationality []){
struct student st;
memcpy(st.lastname,lastname,strlen(lastname));
memcpy(st.firstname,firstname,strlen(firstname));
st.mNr=matNr;
memcpy(st.courseOfStudy,courseOfStudy, strlen(courseOfStudy));
memcpy(st.nationality,nationality,strlen(nationality));
printf("%s,%s,%d\n",st.lastname,st.firstname,st.mNr);
return st;
}
//coping input by reference
void insert_student(struct student * st){
*ptrDb=*st;
ptrDb++;
}
bool delete_entry(int matNr){
int new_size=size-1;
int indexToRemove;
int i;
printf("look for the matriculation number: %d in the Database:\n",matNr);
for (i=0;i<size;i++){
if((db+i)->mNr==matNr){
printf("student found\n");
printf("new database size: %d:\n",new_size);
indexToRemove=i+1;
struct student * temp = (struct student *) malloc((new_size)*sizeof(struct student));
memcpy(temp,db,indexToRemove-1);// copy all elements before indexToRemove
memcpy(temp+indexToRemove,db+indexToRemove+1,size-indexToRemove+1);//copy all elements after indexRemoved
int j=0;
for(j=0;j<new_size;j++){
puts("YES");
printf("lastname: %s, firstname:%s, enrollment nr:%d\n",(temp+j)->lastname,(temp+j)->firstname,(temp+j)->mNr);
}
free(db);//free the old dynamic memory
db=temp;//now db is pointing to the new dynamic memory
free(temp);//I dont need temp any more, free it
return 1;
}
}
return 0;
}
【问题讨论】:
-
是的,已经更新了