问题描述
我正在尝试使用链表实现来实现堆栈.它给了我分段错误".请帮助我找到错误.这是我的代码:
I'm trying to implement stack using linked list implementation. Its giving me "Segmentation Error". Please help me finding the error. This is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 100
struct NODE {
char word;
struct NODE *next;
};
struct STACK {
struct NODE *head;
int size;
};
void pushStack(struct STACK *stack, char s);
void makeStack(struct STACK *stack, char *s);
void printStack(struct STACK *stack);
int main(){
char *s;
fgets(s,100,stdin);
struct STACK stack;
stack.head = NULL;
makeStack(&stack,s);
printStack(&stack);
return 0;
}
void pushStack(struct STACK *stack, char s){
struct NODE temp;
temp.word = s;
temp.next = stack->head;
stack->head = &temp;
}
void makeStack(struct STACK *stack, char *s){
char temp[MAX];
strcpy(temp,s);
for(int i=0; i<MAX; i++){
if(temp[i]=='\0') break;
pushStack(stack,temp[i]);
}
}
void printStack(struct STACK *stack){
struct NODE *trav = stack->head;
while (trav != NULL){
printf("%c", trav->word);
trav = trav->next;
}
}
MAX = 100是我对字符串输入的限制.我还没有添加增加大小的功能,因为我现在暂时忽略了大小的增加.在我完善实施之前
MAX=100 is the limit I'm taking for string input. I haven't also added increasing the size because I'm just ignoring the increment of size for now. Before I could perfect the implementation
推荐答案
在 main
中, s
指针未初始化,并且指向无处.
In main
the s
pointer is not initialized and it points nowhere.
int main(){
char *s; // <<< this is wrong, you want 'char s[100]' instead
fgets(s,100,stdin);
...
但这是最安全的选择:
int main(){
char s[100]; // declare array of 100 chars
fgets(s, sizeof(s), stdin); // sizeof(s) is the actual size of s (100 here)
...
这也是错误的:您将指针存储到本地变量 temp
,但是一旦从 pushStask
函数返回,该变量便不复存在.
This is wrong too: you store the pointer to the local variable temp
, but that variables ceases to exist once you return from the pushStask
function.
void pushStack(struct STACK* stack, char s) {
struct NODE temp;
temp.word = s;
temp.next = stack->head;
stack->head = &temp;
}
相反,您需要像这样创建一个新的 struct NODE
:
Instead you need to create a new struct NODE
like this:
void pushStack(struct STACK* stack, char s) {
struct NODE* temp = malloc(sizeof *temp);
temp->word = s;
temp->next = stack->head;
stack->head = temp;
}
您可以编写 sizeof(struct NODE)
而不是 malloc(sizeof * temp)
,它是相同的,但是它不够安全,因为您可能会错误地编写 sizeof(struct STACK)
可以正常编译,但是分配的内存大小错误.
Instead of malloc(sizeof *temp)
you could write sizeof(struct NODE)
, it's the same, but it's less fool proof because you could mistakenly write sizeof(struct STACK)
which would compile fine, but the size of the allocated memory would be wrong.
另一个问题:您没有分配 struct STACK
的 size
字段,现在这不是问题,但是以后可能会成为问题.
Another problem: you don't assign the size
field of the struct STACK
, this is not a problem now, but it might become a problem later.
这篇关于链表实现中的堆栈错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!