【发布时间】: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;
感谢您的时间和帮助! 干杯
【问题讨论】:
-
我没有看到这个问题。
head似乎正在改变:coliru.stacked-crooked.com/a/baf503d3389a8cac -
代码看起来很正常。也许你的调试器有问题。
标签: c++ list pointers structure