C 中的分段错误,用于使用带有指针的数组的堆栈实现



我有这段代码,用于使用带有指针的数组实现堆栈,该数组执行许多操作,如推送、窥视、弹出、销毁。 我已经通过全局声明 Stack 和 Stacktop 来完成了这一点,当时它起作用了,但现在我想使用指针来实现这个实现,所以这是我的代码:

#include <stdio.h>

int Full(int Stack[], int *StackTop, int *StackSize){
if (*StackTop == *StackSize-1){
return 1 ;
}
else{
return 0;
}
}

int Empty(int Stack[], int *StackTop){
if (*StackTop == -1){
return 1 ;
}
else{
return 0;
}
}

void PushStack(int ele, int Stack[], int *StackTop, int *StackSize){
if (!Full(Stack, &StackTop, &StackSize)){
Stack[++(*StackTop)]= ele ;
}
else{
printf("Error: Stack is full");
}
}

int PopStack(int Stack[], int *StackTop){
if(!Empty(Stack, &StackTop)){
printf("%d popped !",Stack[*StackTop--]);
}
else{
printf("Error : Stack is Empty");
}
}

void PeepStack(int Stack[], int *StackTop){
if(!Empty(Stack, &StackTop)){
printf("%d", Stack[*StackTop])  ;
}
else{
printf("Error : Stack is Empty");
}
}

int DestroyStack(int Stack[], int *StackTop){
printf("Destroying Stackn");
if (!Empty(Stack, &StackTop)){
while(!Empty(Stack, &StackTop)){
PopStack(Stack, &StackTop);
printf("n");
}
}
else{
printf("Stack is already Empty");
}
}

int DisplayStack(int Stack[], int *StackTop){
int i ;
if(Empty(Stack, &StackTop)){
printf("Stack is Empty");
}
else{
printf("Displaying Stack ....n");
for(i=StackTop; i>=0; --i){
printf("| %d |n",Stack[i]);
}
}
}


int main(void) {
int StackSize = 5 ;
int Stack[5] ;
int StackTop = -1 ;
int *Top = &StackTop ;
int *Size = &StackSize ;
while(1){
int option, ele ;
printf("n Options : n");
printf("1. Push n");
printf("2. Pop n");
printf("3. Peep n");
printf("4. Destroy n");
printf("5. Display n");
printf("6. Exit n");
printf("Enter Option number : ");
scanf("%d", &option);
switch(option){
case 1 :
printf("Enter element you want to push : ");
scanf("%d", &ele);
PushStack(ele,&Stack,&Top, &Size);
break;

case 2 :
PopStack(Stack, &Top);
break;

case 3 :
PeepStack(Stack, &Top);
break;

case 4 :
DestroyStack(Stack, &Top);
printf("Stack Destroyed succesfully !");
break ;

case 5 :
DisplayStack(Stack, &Top);
break;

case 6 :
break ;

default:
printf("Invalid option");

}
printf("n");
if(option==6){
break;
}
}
return 0;
}

当我在 repl.it 上执行此操作时,我能够给出第一个输入,即选项编号,但随后它给了我一个分段错误,但是当我在代码块上执行此操作时,我得到返回的进程带有一些数字和一个十六进制代码。

那么这段代码有什么问题呢? 由于哪一行我收到此错误?

你在指针上使用&运算符,这使得指针成为指向指针的指针。

基本上你拥有的模式是这样的:

void Foo(int *bar)
{
*bar = 123;
}
int main()
{
int thing;
int *p = &thing;   // p points to thing
Foo(&p);
printf("%d", &p);  // your expected output is: 123
}

但取而代之的是:

Foo(&p);

你想要:

Foo(p);

因为p已经是一个指针。

但是如果你想使用thing你需要写:

Foo(&thing);

因为&thing指向thing就像p指向thing一样。

最新更新