C++ Pointers to Structure
https:gi.www//iftidea.com
In C++, we can create pointers to structures. This allows us to dynamically allocate memory for a structure and access its members using the pointer. Here's an example:
#include <iostream> using namespace std; struct Person { string name; int age; }; int main() { // create a pointer to a Person structure Person* ptr = new Person; // access structure members using the pointer ptr->name = "John"; ptr->age = 25; // print structure members cout << "Name: " << ptr->name << endl; cout << "Age: " << ptr->age << endl; // free the memory allocated to the structure delete ptr; return 0; }
In this example, we first create a pointer to a Person
structure using the new
operator. We then access the structure members using the pointer using the ->
operator. Finally, we free the memory allocated to the structure using the delete
operator.