如果这是个很容易解决的问题,我真的很抱歉,但我是个初学者。我有个任务要写一些函数到堆栈结构。结构是给出的。我无法排除push()行“s->元素”中的分段错误.我不知道在搜索和搜索几个小时后有什么问题。
在这里,代码:
#define STACK_SIZE 5
#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;
}发布于 2015-03-31 18:42:52
将指针传递给函数时,该函数将接收指针的副本。这通常是很好的,除非您正在更改/创建指针的开始地址。
在您的示例中,sA和sB不包含任何地址(当您将它们传递给initialize时,它们是指向任何内容的指针)。因此,您的initialize函数必须使用指针的地址,而不是指针本身的,才能为将在main中可见的指针分配一个地址。例如:
void initialize(stack **s)
{
stack *newStack;
newStack = malloc(sizeof(*newStack));
newStack->count = 0;
*s = newStack;
}
...
initialize (&sA);删除上面的双指针**s (例如*s = newStack;),将newStack的地址指定为指针s的值。
我还建议在将newStack的位置分配给*s之前检查分配是否成功。
void initialize(stack **s)
{
stack *newStack;
if (!(newStack = malloc(sizeof(*newStack)))) {
fprintf (stderr, "%s() error: memory allocation failed.\n", __func__);
exit (EXIT_FAILURE);
}
newStack->count = 0;
*s = newStack;
}https://stackoverflow.com/questions/29375859
复制相似问题