C++ Pointer to a Structure | Examples

We will study and comprehend the idea of a structure pointer (pointer to a structure) in this tutorial chapter. In order to do this, one must first understand the C++ concept of pointers and structures. Pointers are typically variables that contain the addresses of other variables. A user-defined datatype called a “structure” is essentially a grouping of variables of various types with a single name.

A type of pointer called a “structure pointer” holds the address of a variable with a structure type. We have a structure called a Complex with two data members¬†(one of type float and one of type integer), as you can see in the diagram above. A memory space is allotted when we create a variable of this structure (Complex var1). Now that a pointer of the same structure type (Complex *ptr) as that depicted in the diagram has been created, it is possible to access this memory. Now that this pointer has access to the structure variable var1’s actual memory address, it can access its values.


Example:

#include <iostream>
#include <string>
using namespace std;

// Define a structure called 'Person'
struct Person {
  string name;
  int age;
};

int main() {
  // Declare a pointer to a Person structure
  Person* personPtr;

  // Dynamically allocate memory for a Person structure
  personPtr = new Person;

  // Access and modify structure members using the pointer
  personPtr->name = "John Doe";
  personPtr->age = 25;

  // Print the structure members
  cout << "Name: " << personPtr->name << endl;
  cout << "Age: " << personPtr->age << endl;

  // Deallocate memory for the structure
  delete personPtr;

  return 0;
}
OUTPUT:
Name: John Doe    
Age: 25

In this example, we define a structure called Person with two members: name of type string and age of type int. Inside the main function, we declare a pointer personPtr to a Person structure. We then dynamically allocate memory for a Person structure using the new operator and assign the address to personPtr.

We can access the members of the structure using the arrow operator (->) since personPtr is a pointer. We set the name and age members of the structure using the pointer.

Finally, we print the values of the structure members using the cout object from the <iostream> header. After we’re done using the dynamically allocated structure, we deallocate the memory using the delete operator.

Note that it’s essential to deallocate the memory for dynamically allocated structures to prevent memory leaks.

Leave a Reply

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