我是新的程序员。我正在尝试编写一个小型学生数据库,使用struct的概念结合动态内存(malloc,free ...)。所以我创建了一个struct student,并分配了一个固定大小的动态数组。
但我有一个问题。当我插入新学生然后打印数据库时,我得到一个只填充最后一个条目的数组。
例如:
insert(a1,a2,1)
insert( b1,b2,2)
-> so i get the following:
first-student: b1, b2, 1
second-student: b1, b2,2
我在插入功能中可能是个错误。
display()-Function
通常正常。我找不到问题
这是代码:
#include <stdlib.h>
#include <stdio.h>
struct student{
char * lastname;
char * firstname;
int mNr;
};
struct student * db;
struct student * firstElement;
void createDb(){
db= (struct student *)malloc(3*sizeof(struct student *));
firstElement=db;
printf("database was created\n");
}
struct student getData(char lastname [], char firstname[], int matNr){
struct student st;
st.lastname=lastname;
st.firstname=firstname;
st.mNr=matNr;
printf("%s,%s,%d\n",st.lastname,st.firstname,st.mNr);
return st;
}
void insert_student(struct student * st){
*db=*st;
db++;
}
void delete_student(int immaNr){
}
void search_student(int immaNr){
}
void display(){
db=firstElement;
int i;
for(i=0;i<3;i++){
printf("student %d:\n",i+1);
printf("lastname: %s, firstname:%s, enrollment nr:%d\n",db->lastname,db->firstname,db->mNr);
db++;
}
}
int main(int argc, char ** argv){
char lastname[7];
char firstname[7];
int matNr;
int operation;
createDb();
printf("===================================\n");
printf(" WELCOME TO STUDENT DATABASE \n");
printf("===================================\n");
printf("\n");
begin:
operation=0;
printf("please choose one of these operations:\n");
printf(" (1) enter a new student\n");
printf(" (2) delete a student\n");
printf(" (3) search a student\n");
printf(" (4) show the current database\n");
printf(" (5) exit\n");
scanf("%d",&operation);
switch(operation){
case 1:
printf("enter the lastname\n");
scanf("%s", lastname);
printf("enter the firstname\n");
scanf("%s", firstname);
printf("enter the matriculation number:%d\n",matNr);
scanf("%d",&matNr);
struct student s=getData(lastname,firstname,matNr);
insert_student(&s);
matNr=0;
goto begin;
case 4:
display();
goto begin;
case 5:
puts("exit");
exit(0);
}
}
答案 0 :(得分:0)
好的,这就是这里发生的事情。在您的结构
中struct student{
char * lastname;
char * firstname;
int mNr;
};
您正在存储指向字符数组而不是字符数组的指针,如果您在每次创建新学生时都使用malloc,那么这样做很好,并且执行strcpy()或memcpy()将输入复制到结构中。
但是因为您只是通过引用复制输入,所有学生实例最终都指向最后一个输入的firstname / lastname。像这样改变你的结构
struct student{
char lastname[20];
char firstname[20];
int mNr;
};
在{getData'方法中使用memcpy(st.lastname,lastname,strlen(lastname))
作为lastname和firstname。
或者保留结构的当前实现并将getdata更改为
struct student getData(char lastname [], char firstname[], int matNr){
struct student st;
st.lastname=malloc(strlen(lastname));
memcpy(st.lastname,lastname,strlen(lastname))
st.firstname=malloc(strlen(firstname));
memcpy(st.firstname,firstname,strlen(firstname))
st.mNr=matNr;
printf("%s,%s,%d\n",st.lastname,st.firstname,st.mNr);
return st;
}