🔹 Structure & Pointer Examples in C++

 


In C++, pointers can be used with structures to dynamically access and modify structure members.


1️⃣ Basic Example of Structure & Pointer

📌 Using a pointer to access structure members.

#include <iostream>
using namespace std;

struct Person {
    string name;
    int age;
};

int main() {
    Person p = {"John Doe", 30};
    Person* ptr = &p;

    cout << "Name: " << ptr->name << endl;
    cout << "Age: " << ptr->age << endl;

    return 0;
}

🔹 Output

Name: John Doe
Age: 30

📌 Explanation:
ptr->name is equivalent to (*ptr).name
✔ The arrow operator (->) is used to access members via pointer.


2️⃣ Show Book Details using Structure & Pointer

📌 Dynamically allocate memory for a book structure and display details.

#include <iostream>
using namespace std;

struct Book {
    string title;
    string author;
    double price;
};

int main() {
    Book* b = new Book;

    cout << "Enter Book Title: ";
    getline(cin, b->title);
    cout << "Enter Author: ";
    getline(cin, b->author);
    cout << "Enter Price: ";
    cin >> b->price;

    cout << "\nBook Details:\n";
    cout << "Title: " << b->title << "\nAuthor: " << b->author << "\nPrice: $" << b->price;

    delete b; // Free allocated memory
    return 0;
}

🔹 Output

Enter Book Title: C++ Programming
Enter Author: Bjarne Stroustrup
Enter Price: 49.99

Book Details:
Title: C++ Programming
Author: Bjarne Stroustrup
Price: $49.99

📌 Key Points:
new Book dynamically allocates memory.
delete b is used to free memory.


3️⃣ Find Length using Structure & Pointer

📌 Calculate the length of a line using a structure and pointer.

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

struct Line {
    double x1, y1, x2, y2;
};

double findLength(Line* l) {
    return sqrt(pow(l->x2 - l->x1, 2) + pow(l->y2 - l->y1, 2));
}

int main() {
    Line line;
    cout << "Enter x1, y1, x2, y2: ";
    cin >> line.x1 >> line.y1 >> line.x2 >> line.y2;

    cout << "Length of Line: " << findLength(&line);
    return 0;
}

🔹 Output

Enter x1, y1, x2, y2: 0 0 3 4
Length of Line: 5

📌 Explanation:
✔ Uses distance formula:

length=(x2x1)2+(y2y1)2\text{length} = \sqrt{(x_2 - x_1)^2 + (y_2 - y_1)^2}

✔ Passes structure by pointer for efficiency.


📌 Summary

✔ Use pointers with structures to dynamically access members.
-> is used instead of . for accessing structure members via pointer.
new & delete help manage memory for dynamic structures.

🚀 Need more examples? Let me know! 🔥

Post a Comment

0 Comments