Pointer Assignment

In this class, we will try to understand Pointer Assignment.

Pointer Assignment

We have already discussed the basic concepts of pointer variables and indirection operators in or previous classes.

Pointer Assignment

The pointer variables of the same type can be assigned to each other.

Practice examples

We will try to understand the concept of pointer assignment by using the example, as shown in the image below.

Pointer Assignment Example 1
Pointer Assignment Example 1

We have the visualization of each line of code with their respective images.

After executing the first line of code, the memory space for i, j, p, and q are created, as shown in the image below.

Pointer Assignment First Line Ex 1
Pointer Assignment First Line Ex 1

In the second line of code, pointer p is assigned the address of i. Now p is pointing to ‘i’, as shown in the image below.

Pointer Assignment Second Line Ex 1
Pointer Assignment Second Line Ex 1

In the third line, the pointer variable p is assigned to q.

Here the assignment of the pointer is done where the value in p will get stored in q.

Now q will also point to ‘i’, as shown in the image below.

Pointer Assignment Third Line Ex 1
Third Line Ex 1

In the fourth line of code, using the indirection operator, i is assigned with 10, as shown in the image below.

Pointer Assignment Fourth Line Ex 1
Fourth Line Ex 1

In the fifth line of code, using the indirection operator, i is modified with 20, as shown in the image below.

Pointer Assignment Fifth Line Ex 1
Fifth Line Ex 1

The image below is the second example for practice.

Pointer Assignment Example 2
Pointer Assignment Example 2

After executing the first line of code, the memory space for i, j, p, and q are created, as shown in the image below.

Pointer Assignment First Line Ex 2
First Line Ex 2

In the second and third lines of code, pointer p and pointer q are assigned the ‘address of’ i and, j respectively.

Pointer Assignment Second and Third Line Ex 2
Second and Third Line Ex 2

In the fourth line, the variable i is assigned to 1.

Pointer Assignment Fourth Line Ex 2
Fourth Line Ex 2

In the fifth line, the value stored in the memory location where the pointer variable p is pointing is assigned to the pointer variable q using the indirection operator.

Pointer Assignment Fifth Line Ex 2
Fifth Line Ex 2

In the sixth line, the value stored in pointer variable p, the address 100, is assigned to the pointer variable q.

Now the pointer variable q is pointing to the new location, as shown in the image below.

Pointer Assignment Sixth Line Ex 2
Sixth Line Ex 2

In the seventh line of code, the value in the memory location to which the pointer variable q is pointing is updated to 2.

Pointer Assignment Seventh Line Ex 2
Seventh Line Ex 2