【发布时间】:2019-02-28 07:36:11
【问题描述】:
当我编译并即将推送元素时,我收到分段错误。 什么是分段错误?谁能解释一下这种类型的错误。 和内存处理有关吗?
#include<iostream>
#define MAX 10
using namespace std ;
typedef struct
{
int items[MAX] ;
int top=-1;
}node;
int isFull(node *s){
if (s->top==MAX-1)
{
return 1 ;
}
else{
return 0;
}
}
int isEmpty(node *s){
if (s->top==-1)
{
return 1 ;
}
else{
return 0;
}
}
void push(node *s , int );
void pop(node *s);
void push(node *s , int n ){
if (isFull(s))
{
cout<<"Stack overflow"<<endl;
}
else{
s->items[++(s->top)]=n;
}
}
void pop(node *s){
if(isEmpty(s)){
cout<<"The stack is empty";
}
else{
cout<<"item poppe is "<< s->items[s->top--] <<endl;
}
}
int main(){
int num, choice ;
node *s ;
int flag ;
do{
cout<<"Enter your choice"<<endl;
cout<<"1.Push"<<endl;
cout<<"2.POP"<<endl;
cout<<"3.Exit"<<endl;
cin>>choice;
switch(choice){
case 1 :
cout<<"Enter the number to insert "<<endl;
cin>>num;
push(s,num );
break ;
case 2 :
pop(s);
break ;
default:
cout<<"Error";
break;
}
}
while(flag!=0);
return 0 ;
}
错误是:
分段错误
Program finished with exit code 139
什么是分段错误? C和C++有区别吗?分段错误和悬空指针有什么关系?
【问题讨论】:
-
内部
main(),node *s;:s未初始化 -
main函数中有一个指针变量s。但是它指向哪里?
标签: c++ data-structures stack