当我使用点运算符访问堆栈的元素时,代码运行良好。但是在使用指针访问堆栈结构时,我得到了这个错误。zsh:总线错误/array_stack。有人能帮我解决这个问题吗。代码如下:
#include<iostream>
using namespace std;
//implementing the stack using an array
struct Stack{
int size;//size of the array
int top;//points to the last element of the array
int * arr;
};
int IsEmpty(struct Stack *ptr){
if(ptr->top == -1){
return 1;
}
else{
return 0;
}
}
int main(){
//one way of making the stack
// struct Stack S;
// S.size=43;
// S.top=-1;
// S.arr=(int *)malloc(S.size*sizeof(int));
//second way of making the stack
struct Stack *S;
S->size=54;
S->top=-1;
S->arr=(int *)malloc(S->size*sizeof(int));
if(IsEmpty(S)){
cout<<"The array is empty.";
}
return 0;
}
C
(而不是C++
(。我仍然不确定它会朝哪个方向发展。当答案清楚的时候,我会修改为使用C++。
问题是,您将S
定义为指向Stack的指针,但从未告诉它指向任何东西。因此,S
指向内存中的某个位置(您可能不拥有(,而S->size = 54
正试图通过写入54
来修改该内存的内容。
代码正在生成一个";总线错误";指示CCD_ 7实际上包含在有效存储器范围之外的存储器地址。
要修复它,S
应该指向一个堆栈:
struct Stack myStack; // myStack is an actual stack
struct Stack *S = &myStack; // a pointer to myStack
显然,这个方法创建了一个未初始化的Stack
。做这类事情的一个好方法是创建一个函数,创建一个新的Stack
,初始化它,然后返回一个指向它的指针:
struct Stack *createStack( int capacity )
{
assert( capacity > 0 );
struct Stack *new_stack = malloc( sizeof( struct Stack ) );
if ( new_stack != NULL )
{
new_stack->size = capacity;
new_stack->top = -1;
new_stack->arr = malloc( capacity * sizeof( int ) );
// If we failed to allocate array memory: clean-up & return NULL
if ( new_stack->arr == NULL )
{
free( new_stack );
new_stack = NULL;
}
}
return new_stack;
}
// Matching function to free a stack allocated by createStack()
void freeStack( struct Stack *s )
{
assert( s != NULL );
assert( s->arr != NULL );
free( s->arr ); // release the array part first
free( s ); // release the struct itself
}
然后在你的代码中,它可以被称为:
struct Stack *s = createStack( 54 );
// ...
freeStack( s ); // clean up when done