【发布时间】:2020-04-23 11:22:56
【问题描述】:
我正在使用 GList(双重)实现一个堆栈,但是当我使用 g_list_last(*stack*) 为堆栈分配最后一个元素时,程序根本不会打印我的堆栈
使用g_list_first(*stack*) 指向第一个元素有效,我可以使用堆栈遍历->下一个指针
这是我的测试程序:
#include <iostream>
#include <cstdlib>
#include <glib.h>
using namespace std;
int main()
{
cout << "Enter the no of random data to push: ";
int number = 0;
cin >> number;
GList *stack = nullptr;
for (int i = 0; i < number; i++) {
int data = random() % 10;
stack = g_list_append(stack, GINT_TO_POINTER(data));
cout << "Push: " << data << endl;
}
cout << "Printing the stack forward:\n";
stack = g_list_first(stack);
while (stack != nullptr) {
cout << GPOINTER_TO_INT(stack->data);
cout << "->";
stack = stack->next;
}
cout << "nullptr" << endl;
cout << "Printing the stack backward:\n";
stack = g_list_last(stack);
while (stack != NULL) {
cout << GPOINTER_TO_INT(stack->data);
cout << "->";
stack = stack->prev;
}
cout << "nullptr" << endl;
return 0;
}
我必须在附加时手动分配上一个链接吗?
【问题讨论】:
-
我对 glist 了解不多,但我怀疑,由于将未初始化的指针传递给
g_list_append,您正在调用未定义的行为。 -
@AlgirdasPreidžius 刚刚将 nullptr 分配给我的堆栈并现在对其进行测试。不,问题仍然存在:(
-
未定义的行为并不意味着它总是会破坏行为。它也可能以您期望的方式工作。因此,在上述修复之后,您的代码很可能有一个问题,而不是两个。
-
更新代码:)以避免错误