我嘗試製作關於學生註冊的程序。嘗試調用我的deleteStudent函數時出現分段錯誤(核心轉儲)
這是我的頭文件:
#ifndef STUDENTREGISTRATION_H_
#define STUDENTREGISTRATION_H_
typedef struct {
char name[30];
char surname[30];
char faculty[30];
char department[30];
int age;
int grade;
int count;
} STUDENT_STRUCT, *STUDENT;
STUDENT_STRUCT students[100];
STUDENT_STRUCT empty;
void *data_init();
void *data_set(STUDENT s);
void addStudent(int count,STUDENT s);
void displayList(int count);
void free_list(STUDENT s);
void deleteStudent(int index,int count);
void Choice();
#include <stdio.h>
#include <stdlib.h>
#include "string.h"
#include "StudentREGISTRATION.h"
void *data_set(STUDENT s) {
s = students;
return s;
}
void addStudent(int count,STUDENT s) {
printf("Please enter an information about student:\n");
printf("Name:");
scanf("%s", s->name);
printf("Surname:");
scanf("%s", s->surname);
printf("Faculty:");
scanf("%s", s->faculty);
printf("Department:");
scanf("%s", s->department);
printf("Age:");
scanf("%d", &s->age);
printf("Grade:");
scanf("%d", &s->grade);
students[count].age = s->age;
students[count].grade=s->grade;
strcpy(students[count].department,s->department);
strcpy(students[count].faculty,s->faculty);
strcpy(students[count].name,s->name);
strcpy(students[count].surname, s->surname);
free_list(s);
}
void displayList(int count) {
int i;
for (i = 0; i < count; i++) {
if(students[i].name[0] != "\0" && students[i].surname[0] != "\0" && students[i].faculty[0] != "\0" && students[i].department[0] !="\0"&&students[i].age != 0 && students[i].grade != 0)
{
printf("%d.) %s %s %s %s %d %d \n", i + 1, students[i].name,
students[i].surname, students[i].faculty,
students[i].department, students[i].grade, students[i].age);
}
}
}
void free_list(STUDENT s) {
free(s);
}
void deleteStudent(int index,int count) {
int i;
for(i=0;i<count;i++)
{
if(index-1==i)
{
students[i].name[0]="\0";
students[i].surname[0]="\0";
students[i].department[0]="\0";
students[i].faculty[0]="\0";
students[i].age=0;
students[i].grade=0;
}
}
displayList(count);
}
void *data_init()
{
STUDENT s=(STUDENT)malloc(sizeof(STUDENT_STRUCT));
return s;
}
void Choice() {
STUDENT s;
int a=0;
printf("Enter your choice to do with a program\n");
printf("Press A for adding student\n");
printf("Press L to display a student list\n");
printf("Press D for deleting student\n");
printf("Press E for exit\n");
char choice = ' ';
int index;
while (choice != 'E') {
printf("Your choice:");
scanf("%c", &choice);
switch (choice) {
case 'A':
s=data_init(s);
addStudent(a,s);
a++;
break;
case 'L':
displayList(a);
break;
case 'D':
printf("Enter an index:");
scanf("%d ",index);
deleteStudent(index,a);
break;
}
}
exit(1);
}
我得到分段錯誤(代碼轉儲)錯誤,當程序試圖運行在交換機的情況下刪除功能。在這段代碼中我的錯在哪裏,我想它是關於指針的一切。但我嘗試爲每個學生分配和釋放。問題在哪裏,如果有人告訴我,我會感激。謝謝。
而且,我的main()調用了Choice()函數來運行程序。對不起這是我的錯。 – 2014-11-04 19:04:41
@ user3121023這應該是一個答案,而不是評論。 – 2014-11-04 19:10:43