Sam*_*del 1 c++ stack data-structures
虽然我编译并即将推送元素我得到分段错误.什么是分段错误?任何人都可以向我解释这种类型的错误.它与内存处理有关吗?
#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 ;
}
Run Code Online (Sandbox Code Playgroud)
错误是:
分段故障
Program finished with exit code 139
Run Code Online (Sandbox Code Playgroud)
什么是分段错误?C和C++有什么不同吗?分段错误和悬空指针是如何相关的?
您定义了一个指向节点的指针(实际上是一个完整的堆栈),但是您不创建此指针可指向的节点对象.因此,您取消引用未初始化的指针,这会产生未定义的行为(例如,段错误).
代替
node *s ;
...
push(s,num );
Run Code Online (Sandbox Code Playgroud)
写
node s ;
...
push(&s,num );
Run Code Online (Sandbox Code Playgroud)
要么
node *s = new node(); // or = malloc(sizeof(node)) in C
...
push(s,num );
...
// once the stack is not used any more:
delete s; // or free(s) in C.
Run Code Online (Sandbox Code Playgroud)
这样你就可以创建一个实际的对象,然后你可以传递这个地址.