【发布时间】:2015-11-09 20:29:49
【问题描述】:
我一直在尝试使用指向指针的指针来执行类似于树中的中序遍历的操作。这是我的代码
struct node {
char c = '\0';
int freq = 0;
node *left = NULL;
node *right = NULL;
string code = "";
};
void appendones(node **n) {
if ((*n) == NULL)
;
else {
(*n)->code += "1";
appendones(&(*n)->left);
appendones(&(*n)->right);
}
}
void combinenodes(node *a, node *b, node **n) {
appendones(&a);
appendones(&b);
//(*n)=newNode('\0',a->freq+b->freq);
(*n)->c = '\0';
(*n)->freq = a->freq + b->freq;
(*n)->left = a;
(*n)->right = b;
}
int main() {
N = input();
priority_queue<node, vector<node *>, compareNodefreq> nodefreq; // function object
for (int i = 0; i < N; i++) {
char s;
int freq;
cin >> s >> freq;
node *n = newNode(s, freq);
nodefreq.push(n);
}
// printheap(nodefreq);
// perform combining nodes based on frequencies
while (nodefreq.size() > 1) {
node *a = nodefreq.top();
nodefreq.pop();
node *b = nodefreq.top();
nodefreq.pop();
node *n;
combinenodes(a, b, &n);
nodefreq.push(n);
}
}
我在(*n)->code+="1"; 中遇到appendone() 的分段错误。
我无法找出错误。我的理解是我正在路过
引用指针并执行appendzero() 和appendone(),
所以我想那部分没有错误。还有我的a 和b
combinenodes() 不能为空,因为我正在从堆栈中弹出。
你能帮我弄清楚吗?
【问题讨论】:
-
请修正您的格式并将代码修剪为minimal reproducible example。
-
并尝试自己调试代码。这类错误通常很容易被调试器检测到。
-
@BaummitAugen,已修复,现在可以帮忙吗?
-
您能发布完整的确切段错误消息吗?还有
newNode()? -
使用调试器并阅读关于 C++ 的 book。不给你
new。