The struct problem.
I wrote a code implementing a stack. If I pass sqStack* sq to this function init_stack(), the code ended up with an error. As seen in the comment of the following code.
But then I found out if I pass sqStack &sq to init_stack() function, the code works.
Can anyone explain to me? Thanks!
#include <stdio.h>
#include <stdlib.h>
#define init_size 10
#define increment 1
typedef struct sqStack
{
int* top;
int* base;
int stack_size;
}sqStack;
int init_stack(sqStack* sq)
{
if(sq->base==NULL)
{
sq->base = (int*)malloc(init_size*sizeof(int));
}
if(sq->base==NULL) exit(-1);
sq->stack_size=init_size;
sq->top=NULL;
sq->top=sq->base;
return 1;
}
int push(sqStack* sq, int e)
{
if(sq==NULL) exit(-1);
if(sq->top-sq->base==sq->stack_size)
{
int* q = (int*)realloc(sq->base,
(init_size+increment)*sizeof(int));
if(q==NULL) exit(-1);
sq->base=q;
sq->stack_size += increment;
sq->top=sq->base+sq->stack_size;
}
*sq->top++=e;//Thread 1: EXC_BAD_ACCESS If I pass sqStack* sq to this function, error occurs. But if I pass sqStack &sq, the code works.
return 1;
}
int pop(sqStack* sq,int*e)
{
if(sq==NULL) exit(-1);
if(sq->base==sq->top) exit(-1);
sq->top-=1;
*e=*sq->top;
return 1;
}
int empty(sqStack* sq)
{
if(sq->base==sq->top) return 1;
else return 0;
}
int main()
{
sqStack* sq;
init_stack(sq);
push(sq,1);
int e=
pop(sq,e);
printf("%d\n",*e);
/* sqStack sq;
init_stack(&sq);
push(&sq,1);
int e;
pop(&sq,&e);
printf("%d\n",e);*/
return 0;
}
In either case, the output is 1.
mainfunction you have the pointersq, but where does it point? I recommend you change it to be not a pointer, and use the address-of operator&when a pointer to it is needed.&basically means "pointer to".