【问题标题】:Creating a list in C++在 C++ 中创建列表
【发布时间】:2016-11-27 16:46:14
【问题描述】:

我目前正在学习指针和结构,并且正在做一个练习。 我的目标是编写一个函数 head_insert,它基本上创建一个新的列表元素并将其附加到前面。

注意:我知道 C++ 中已经有一个数据类型列表,但这只是为了更好地练习和理解动态结构背后的概念。

我的代码如下:

struct list{
    int val;
    list *next = NULL;
};

typedef list* ptr_list;

ptr_list head_insert(ptr_list head, const int element){
    ptr_list tmp_head;
    tmp_head = new list;
    tmp_head->val = element;
    tmp_head->next = head;
    return tmp_head;
}

int main(){
    ptr_list head = NULL;
    head = head_insert(head, 1); // This is the crucial step I think, as head is not initialized yet
    head = head_insert(head, 2);

    return 0;
}

问题是,我希望函数 head_insert 在 head 为 NULL 时也能工作,即我的列表为空。但是,在调试我的代码时,我注意到每次调用 head_insert head 后,head 都保持为 NULL,但是在 head(head->val, head->next) 中进行了更改。

这是为什么呢?这与 tmp_head 的范围有关吗? 我怎样才能修改我的代码以按照我的预期工作?

如果我一开始没有将 head 设置为 NULL,而是分配空间并手动将其设置为第一个元素,那么一切正常:

head = new list;
head->val = 1;

感谢您的时间和帮助! 干杯

【问题讨论】:

标签: c++ list pointers structure


【解决方案1】:

您的代码看起来没问题,head 在调用head_insert 后肯定会发生变化。

但是,说

在 head(head->val, head->next) 内进行了更改

错了,你没有从head_insert“改变”头部,你创建了一个新对象tmp_head,然后当head_insert返回时它被分配给head。

当您使用调试器时,您可能注意到head 在head_insert 执行中仍然是NULL,这是绝对正常的。稍后,当函数返回时,tmp_head 被复制到 head(就像您所做的 head = head_insert(head, 1);),然后 head 才从 NULL 更改为不是 NULL。

【讨论】:

  • 感谢您的回答。这很奇怪。 Eclipse 调试器始终显示 head = 0x0。但是,您是对的,当我在每次调用 head_insert 后打印出 head 时,我可以看到它的值实际上正在发生变化。我解决了导致我调试代码的原始问题。它在开始时将指针设置为 NULL。我一开始没有这样做,然后程序在插入/无法在列表上工作(打印出来)后终止。
猜你喜欢
  • 2012-09-19
  • 2016-02-04
  • 2018-06-25
  • 1970-01-01
  • 2010-09-28
  • 1970-01-01
  • 2012-10-27
  • 2015-12-31
  • 2021-12-30
相关资源
最近更新 更多