【发布时间】:2012-01-27 06:14:30
【问题描述】:
我有一些问题。 我尝试此代码并收到“分段错误”错误:
#include <iostream>
#include <cstring>
#include <cctype>
using namespace std;
struct Stack {
int value;
Stack *next;
};
void push(Stack* top, int value) {
Stack *ntop = new Stack;
ntop->value = top->value;
ntop->next = top->next;
top->next = ntop;
top->value = value;
}
int pop(Stack* top) {
int val = top->value;
top->value = top->next->value;
top->next = top->next->next;
return val;
}
int main()
{
Stack *top;
top->next = NULL;
push(top, 20);
cout << pop(top);
}
[10:40:46] [~] >> g++ 3.cpp -o 3 && ./3 分段错误
但如果我在 Stack *top; 之前添加 const char* test = ""; 它可以正常工作:
int main()
{
const char* test = "";
Stack *top;
top->next = NULL;
push(top, 20);
cout << pop(top);
}
[10:47:33] [~] >> g++ 3.cpp -o 3 && ./3 20
我的错在哪里?
【问题讨论】:
-
这只是我的大学练习,我更喜欢 STL
标签: c++ pointers stack segmentation-fault