Sunday, October 20, 2019

about pointer assignment operation.

I never thought about it because I just knew how it works. Today I'll show you why pointer assignment statement in function is not working as intended.

Just assume there is a simple Node class like below.

class Node
{
public:
int data;
};

this Node class will contain integer data variable as a member and has nothing more. Normally Node class has prev, next pointer member but I'll ignore those in this article.

OK, let's create an head and give it a value 10.

Node* head = new Node();
head->data = 10;

now head pointer will point to some address which is sizeof(Node)

to see the address of head. we can do this.

cout << head << endl;   <--- 1
cout << &head << endl; <--- 2

line 1 will print the address of sizeof(Node) which contains Node's value(integer 10)




If you are using Visual Studio then you can use memory viewer and see the content of the memory like below.


As you can see 0x00526ED0 has integer value of 10. Second address which is address of head pointer. 0x002CF718.

Just think about what is there.



D06E5200 is an reverse order of address 0x00526ED0. This is because intel CPU uses little endian.

Anyway 0x002CF718 which is &head, contains the address of sizeof(Node) (actual value)

now if we pass head pointer to other function and assign new Node. see what happen.


void foo(Node* p)
{
cout << p << endl;
cout << &p << endl;

Node* item = new Node();
item->data = 1024;

p = item;
}


As you can see third address is same as sizeof(Node)'s address. but forth address is different. that's address of p pointer!

when we call foo function and pass head pointer as a param like below.


foo(head);

p is a copy of head pointer which is different variable. their target address which is 0x00526ED0 are same but address of itself are different. so somebody wants to change head's target address like this.


p = item;


it is not working properly. if you see memory window then you will see what's changed.


after p = item statement is executed then address will be changed.


ok p's target address is changed but the problem is that address of p and address of head are different! so basically head's target address is not changed.

if we exit foo function then effect(changing address) will be gone. because p = item is actually changed value of p pointer's address.

This is really trivial thing for C/C++ programmer but cumbersome.

if we want to change head pointer's target address then we should pass pointer of pointer of head variable which is Node**

void foo(Node** p)
{
Node* item = new Node();
item->data = 1024;

*p = item;
}

and use it like this.

foo(&head);

or there are different way to change address of head which is returning Node* in the function foo.

Node* foo(Node* p)
{
Node* item = new Node();
item->data = 1024;

return item;
}

head = foo(head);

No comments:

Post a Comment

Task in UnrealEngine

 https://www.youtube.com/watch?v=1lBadANnJaw