c++ - 分段错误:11。急需解决代码(链表)
问题描述
我目前是 C++ 的初学者,从 C 转换而来。但我仍然是编程代码的初学者。
我目前正在寻找可以帮助我找到源代码问题的人(实际上是来自朋友)。源代码似乎在我朋友的编译器(Windows)上运行良好,但我目前在 MacOS Big Sur 上使用 VSCode。
#include <stdio.h>
#include <iostream>
using namespace std;
struct Data_mhs{
char nim[12];
char nilai;
};
struct mhs{
Data_mhs data;
mhs* next;
};
mhs* head;
mhs* tail;
mhs* baru;
mhs* del;
void inisialisasi(){
head=NULL;
tail=NULL;
}
void input(Data_mhs br)
{
baru->data = br; //penugasan struktur
baru->next = NULL;
if(head==NULL)
{
head = baru;
tail = head;
}
else
{
tail->next = baru;
tail=baru;
}
}
void hapus(){
mhs simpan;
if(head==NULL)
{
cout<<"\n(DATA TIDAK ADA YANG DIHAPUS)"<<endl;
}
else
{
simpan.data = head->data;
cout<<"\nData yang dihapus adalah ";
cout<<simpan.data.nim<<"||"<<simpan.data.nilai<<endl;
//hapus depan
del = head;
head = head->next;
delete del;
}
}
void menu(){
char pilih, ulang;
mhs tmp;
start:
cout<<"\nMenu : "<<endl;
cout<<"1. Input data"<<endl;
cout<<"2. Hapus data"<<endl;
cout<<"Masukkan pilihan Anda : ";
cin>>pilih;
switch(pilih)
{
case '1' :
fflush(stdin);
cout<<"\nMasukkan NIM : ";
cin>>tmp.data.nim;
cout<<"Masukkan nilai : ";
cin>>tmp.data.nilai;
input(tmp.data);
break;
case '2' :
hapus();
break;
default :
cout<<"Pilihan salah"<<endl;
}
cout<<"\nKembali ke menu (y/n) ?";
cin>>ulang;
if(ulang=='y'){
goto start;
}
}
int main(){
inisialisasi();
menu();
return 0;
}
代码似乎运行良好,但在我的编译器(MacOS)上运行时代码似乎有问题,代码显示“Segmentation Fault:11”
好像有问题:
baru->data = brr; //penugasan struktur
baru->next = NULL;
如果有人可以帮助解决我的问题,那将是一个很大的帮助!
解决方案
你从来没有分配baru
指向任何东西。当你这样做时,baru->data = brr;
你正在取消引用一个空指针。它是空的,因为全局指针被初始化为空。
推荐阅读
- python - 如果不透明度≠ 1.0,python 中的 Plotly 3d-surface plot opacity error 总是给出透明的
- sql - 多维数据集 SQL ORA-00936 缺少表达式
- java - 如何过滤 TreeMap
>> , - github - 使用 Octokit API 从 GitHub Actions 获取最新的工作流程
- c# - 无法在 .Net 核心中模拟 Auto Mapper
- amazon-web-services - AWS Managed AD SSL 证书导出
- javascript - 使用没有 ID 的 createDocumentFragment()
- q# - 我的 Q# 语言服务器不会停止在 VS Code 上下载
- amazon-web-services - 由于 SNS 主题订阅已存在不同属性,AWS Cloudformation 模板部署失败
- python - 字典的备份计划(在矩阵诊断中)?