Pointer to Structure in C++

In this tutorial chapter we will study and understand the concept and working of a structure pointer (pointer to a structure). For this it is first necessary to know the concept of pointers & structures in C++. In general Pointers are variables that store address of other variables. A structure is a user defined datatype which is essentially a collection of variables of different types under a single name.

C++ Structure Pointer


pointer to structure in c++ programming

A structure pointer is a type of pointer that stores the address of a structure typed variable. As you can see in the above diagram we have a structure named Complex with 2 datamembers (one integer type and one float type). When we create a variable of this structure (Complex var1), it is alotted a memory space. This memory can now be accessed by creating a pointer of the same structure type as shown in the diagram (Complex *ptr). Now this pointer can point the actual memory address of the structure variable var1 and can access its values. Following is an example program for the same:

Run Online

Enter Value of 2-D array A:
Real part: 5
Imaginary part: 0.33
Pointer to Structure Array in C++

As we just saw pointer to a structure variable, a pointer can be used to point to an array of structures and access their values as well.


pointer to structure array in c++

As shown in the above diagram we have created an array of structure type Complex of size 2. We then created a pointer of Complex structure type and assigned the address of array var1 to this pointer. Now the pointer *ptr contains the address of the first element (Base Address) in the structure array var1 and we can use the pointer to access all elements inside the array by iterating the pointer using ptr++. Let us see an example of this:

Run Online

Enter Value of 2-D array A:
Real part of  array element1 : 5
Imaginary part of array element1 : 0.33
Real part of  array element1 : 7
Imaginary part of array element1 : 0.56

Leave a Reply

Your email address will not be published. Required fields are marked *