如果这是一个容易解决的问题,我真的很抱歉,但我是初学者。 我有一项任务是将一些函数写入堆栈结构。给出了结构。我无法摆脱 push() 行“s->elements...”中的段错误 经过几个小时的谷歌搜索和搜索后,我不知道出了什么问题。
这里是代码:
#define STACK_SIZE 5<p></p>
#include <stdio.h>
#include <stdlib.h>
typedef struct stackADT {
int elements[STACK_SIZE];
int count;
} stack;
void initialize(stack *s)
{
stack *newStack;
newStack = malloc(sizeof(*newStack));
newStack->count = 0;
s = newStack;
}
int push(stack *s, int value)
{
if(s->count == 5) return -1;
else {
s->elements[s->count++] = value;
return s->elements[s->count-1];
}
}
int main()
{
stack* sA;
stack* sB;
initialize(sA);
initialize(sB);
printf("%d\n",push(sA,3));
return 0;
}
最佳答案
我认为你需要像下面这样的东西
#include <stdio.h>
#define STACK_SIZE 5
typedef struct stackADT
{
int elements[STACK_SIZE];
int count;
} stack;
void initialize( stack *s )
{
s->count = 0;
}
int push( stack *s, int value )
{
return s->count == STACK_SIZE ? -1 : ( s->elements[s->count++] = value );
}
int main(void)
{
stack sA;
stack sB;
initialize( &sA );
initialize( &sB );
printf( "%d\n", push( &sA, 3 ) );
return 0;
}
关于C - 结构段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29375859/