Srujan Barai
Srujan Barai

Reputation: 2365

Equating pointer value is changing pointer reference

struct node
{
    char *ptr = (char *)malloc(frames*sizeof(char));
}*start,*current;

Then I have allocated memory equal to node to start.

[...]//Assigned values to start node.
current = start;//Current points to start
node *temp = new node();//temp will point a newly created node
*temp = *current;//    COPYING VALUES OF CURRENT TO TEMP
[...]

I want to create a new node, make temp point to it and copy values of current (here current is pointing to start) to temp.

BUT this is making temp point current (here start) instead. Frustrated. Where am I going wrong?

Upvotes: 0

Views: 705

Answers (2)

unknown
unknown

Reputation: 251

There could be two solutions

  1. Change *temp=*current to temp=current. Doing this, you can access values of "current" using "temp" as these two pointers are now referring to the same memory location. Caution, changing value by using "current" or "temp" will cause to change in value in both pointers as they are referring to same memory location.
  2. Use memcpy. It will copy values from one memory location to other. Here is the reference. Now you have two independent copies of values.

Upvotes: 0

Rahul
Rahul

Reputation: 3509

*temp = *current should be temp = current.

Upvotes: 2

Related Questions