miodi 2020-03-16 18:55 采纳率: 0%
浏览 147

我用链表进行插入语删除操作后,发生了越界,我的代码哪里错了吗?

#include
#include
#include
#include
#include
typedef struct Student{
char num[10]; //学号
char name[10]; //姓名
char gender[2]; //性别
int age; //年龄
}Student;

//链表的定义
typedef struct LNode{
Student* data; //存放学生信息的数据域
struct LNode *next; //指向下一个学生信息的指针域
}LNode,*linklist;

void input(int n, LNode **head){
if(n <= 0){
printf("输入错误\n");
return;
}
LNode p = *head = (LNode)malloc(sizeof(LNode));
int i;

for(i = 0; i < n; i++){
p->next=(LNode*)malloc(sizeof(LNode));
p->next->data = (Student*) malloc (sizeof(Student));
p->next->next = NULL;
scanf("%s %s %s %d",p->next->data->num, p->next->data->name, p->next->data->gender, &p->next->data->age);
p = p->next;
}
return;
}

//输出学生信息
void output(LNode p){
p=p->next;
while(p!= NULL){
printf("%s %s %s %d\n",p->data->num, p->data->name, p->data->gender, p->data->age);
p = p->next;
}
printf("\n");
}
//插入信息
void add(LNode *head, int n){
if(n<1){
printf("输入过小\n");
return;
}
LNode *p = (LNode
)malloc(sizeof(LNode));
p->next = NULL;
scanf("%s %s %s %d",p->data->num, p->data->name, p->data->gender, &p->data->age);
int i = 1;
while(head!=NULL){
if(i == n){
p->next = head->next;
head->next = p;
break;
}
head = head->next;
i++;
}
if(head==NULL){
head->next = p;
}
}
//链表的删除
int del(LNode head, int n,int sum){
if(n printf("输入过小\n");
return -1;
}
if(n>sum){
printf("输入过大\n");
return -1;
}
linklist p;
p = (LNode
)malloc(sizeof(LNode));
int i = 1;
while(i<=n-1) {
head=head->next;
i++;
}
p=head->next;
head->next=head->next->next;
free(p);
return 1;
}

int main(void){
LNode *head = NULL;
printf("请输入学生人数:");
int sum;
scanf("%d",&sum);
printf("请依次输入学号,姓名,性别,年龄:\n");
input(sum,&head);
output(head);

printf("请输入插入位置:");
int a;
scanf("%d",&a);
add(head,a);
sum++;
output(head);

printf("请输入删除位置:");
int b;
scanf("%d",&b);
int temp;
temp=del(head,b,sum);
if(temp==1){
    sum--;
}
output(head);

return 0; 

}

  • 写回答

1条回答 默认 最新

  • 时光放逐 2020-03-16 20:11
    关注

    LNode* p = (LNode*)malloc(sizeof(LNode));//这样才是分配一块LNode大小的内存并定义指针指向该内存

    评论

报告相同问题?

悬赏问题

  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况
  • ¥15 画两个图 python或R