gpt4 book ai didi

c++ - 我不断在链接列表上收到段错误

转载 作者:太空狗 更新时间:2023-10-29 20:22:42 26 4
gpt4 key购买 nike

该程序应该生成用户输入的 n 数字的随机链表,但是当它尝试打印链表时出现段错误。

程序一直运行到它必须显示链表为止。

#include <iostream>

class node
{
public:
// TYPEDEF
typedef double value_type;

// CONSTRUCTOR
node(
const value_type& init_data = value_type(),
node* init_link = NULL
)
{ data_field = init_data; link_field = init_link; }

// Member functions to set the data and link fields:
void set_data(const value_type& new_data) { data_field = new_data; }
void set_link(node* new_link) { link_field = new_link; }

// Constant member function to retrieve the data:
value_type data() const { return data_field; }

// Constant member functions to retreive the link:
node* linker() const { return link_field; }

private:
value_type data_field;
node* link_field;
};

int myrand(int)
{
return(1 + rand() %(1000 - 1 +1));
}

void print_linked_list(node*& head_ptr, node*& print_ptr, size_t n)
{
for (size_t i =1 ; i <= n ; i++) {
head_ptr = new node(myrand(n), head_ptr);
}
std::cout << "Unsorted List: " << std::endl;
for (print_ptr = head_ptr; print_ptr !=NULL; print_ptr = print_ptr->linker()) {
std::cout << print_ptr->data() << " ";
}
}

int main()
{
size_t n;
srand(time(NULL));

node* head_ptr;
node* print_ptr;

std::cout << "Please input a number" << std::endl;
std::cin >> n;

print_linked_list(head_ptr, print_ptr, n);

return 0;
}

最佳答案

您正试图访问一个未初始化的指针。您为 print_linked_list 函数提供了未初始化的 head_ptr 变量。然后在创建第一个节点时使用该值作为指向下一个节点的指针。这意味着永远不会满足条件 print_ptr != NULL

这可以通过在 main 中声明时将 head_ptr 设置为 NULL 来解决。

关于c++ - 我不断在链接列表上收到段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36587194/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com