Doc Doc - 1 year ago 64
C++ Question

Creating a list in C++

I am currently learning about pointers and structures, and I am working on an exercise.
My goal is to write a function head_insert which basically creates a new list element and it appends it to the front.

Note: I know that there's already a datatype list in c++, however this is just for exercising and understanding the concept behind dynamic structures better.

My code is the following:

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;

The thing is, I want the function head_insert also to work when head is NULL, i.e. my list is empty. However, when debugging my code, I notice that after each call of head_insert head stays NULL, however changes within head(head->val, head->next) are made.

Why is that? Has that something to do with the scope of tmp_head?
How could i modify my code to work in the way I intended?

If I dont set head to NULL in the beginning, but allocate space and setting it manually to the first element, everything works perfectly fine:

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

Thanks for your time and help!

Answer Source

Your code looks OK and headdefinitely changes after head_insert is called.

However, saying

changes within head(head->val, head->next) are made

is wrong, you don't "change" head from head_insert, you create a new object tmp_head and later it's assigned to head when head_insert returns.

When you were using your debugger, you probably noticed that head remains NULL within head_insert execution, which is absolutely normal. Later, when the function returns, tmp_head is copied to head (as you did head = head_insert(head, 1);) and only then head is changed from NULL to something not NULL.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download