Declaration of Structure in C++
A structure (struct) in C++ is a user-defined data type that groups variables of different data types under a single name.
A structure (struct) in C++ is a user-defined data type that groups variables of different data types under a single name.
1. Basic Declaration of a Structure
Syntax
struct structure_name {
data_type member1;
data_type member2;
...
};
⚠ Semicolon (;) is mandatory after the structure definition.
Example
struct Student {
int roll;
char name[20];
float marks;
};
✔ Student is a new data type.
2. Declaring Structure Variables
Method 1: After Structure Definition
Student s1, s2;
Method 2: At the Time of Structure Declaration
struct Employee {
int id;
float salary;
} e1, e2;
3. Accessing Structure Members
Use the dot (.) operator.
s1.roll = 101;
s1.marks = 85.5;
4. Structure Declaration Inside main()
int main() {
struct Book {
int pages;
float price;
};
Book b1;
}
✔ Scope limited to main().
5. Structure Initialization
Student s1 = {1, "Rahul", 90.5};
6. struct in C++ vs C
Feature C C++
struct keyword while declaring variable Required Not required
Member functions ❌ ✔
Access specifiers ❌ ✔
7. Structure with Member Functions (C++ Feature)
struct Rectangle {
int length;
int breadth;
int area() {
return length * breadth;
}
};
8. Typedef with Structure
typedef struct {
int x;
int y;
} Point;
Usage:
Point p1;
9. Important Exam Points
- Structure is a user-defined data type
- Groups different data types
- Semicolon is compulsory
- Members accessed using dot operator
- Supports functions in C++
Initialization of Structure in C++
Structure initialization in C++ means assigning initial values to the members of a structure at the time of declaring a structure variable.
1. Initialization at the Time of Declaration (Basic Method)
Syntax
struct_name variable = { value1, value2, ... };
Example
struct Student {
int roll;
char name[20];
float marks;
};
Student s1 = {101, "Amit", 88.5};
✔ Values are assigned in the order of declaration.
2. Partial Initialization
If fewer values are provided, remaining members are initialized to zero (or null).
Student s2 = {102, "Neha"};
Equivalent to:
marks = 0.0
3. Initialization Using Dot Operator (After Declaration)
Student s3;
s3.roll = 103;
s3.marks = 91.2;
✔ Useful when values are known later.
4. Designated Initialization (C++20)
Allows initializing specific members by name.
Student s4 = {.roll = 104, .marks = 85.0};
✔ Order does not matter.
5. Initialization Using Constructor (C++ Style)
struct Student {
int roll;
float marks;
Student(int r, float m) {
roll = r;
marks = m;
}
};
Student s5(105, 92.3);
✔ Preferred in modern C++.
6. Array of Structures Initialization
Student s[2] = {
{201, "Ravi", 78.5},
{202, "Priya", 88.0}
};
7. Structure Containing Another Structure
struct Date {
int day, month, year;
};
struct Employee {
int id;
Date dob;
};
Employee e1 = {1, {12, 5, 2000}};
8. Initialization Using Pointer to Structure
Student s1 = {301, "Kiran", 90.0};
Student *p = &s1;
cout << p->marks; // 90.0
9. Common Mistakes ❌
- Missing order of members
- Forgetting braces { }
- Using wrong data types
Functions and Structures in C++
In C++, structures and functions work together to organize data and operations efficiently. Functions can use, accept, return, and even be members of structures.
1. Passing Structure to a Function (Call by Value)
A copy of the structure is passed. Changes do not affect the original structure.
#include <iostream>
using namespace std;
struct Student {
int roll;
float marks;
};
void display(Student s) {
cout << s.roll << " " << s.marks << endl;
}
int main() {
Student s1 = {101, 85.5};
display(s1);
return 0;
}
2. Passing Structure to a Function (Call by Reference / Address)
Original structure can be modified.
Using Pointer
void update(Student *s) {
s->marks = 90.0;
}
Call:
update(&s1);
Using Reference (C++ way)
void update(Student &s) {
s.marks = 95.0;
}
3. Returning a Structure from a Function
Student create() {
Student s = {102, 88.0};
return s;
}
Call:
Student s2 = create();
4. Array of Structures Passed to Function
void displayAll(Student s[], int n) {
for(int i = 0; i < n; i++)
cout << s[i].roll << " " << s[i].marks << endl;
}
5. Structure with Member Functions (C++ Feature)
struct Rectangle {
int length, breadth;
int area() {
return length * breadth;
}
};
Usage:
Rectangle r = {5, 4};
cout << r.area(); // 20
6. Pointer to Structure in Functions
void show(Student *s) {
cout << s->roll << " " << s->marks;
}
7. Nested Structures with Functions
struct Date {
int d, m, y;
};
struct Employee {
int id;
Date doj;
};
void display(Employee e) {
cout << e.id << " " << e.doj.y;
}
8. Comparison: Call by Value vs Call by Reference
Feature Call by Value Call by Reference
Copy created Yes No
Original data modified No Yes
Efficiency Less More
9. Key Exam Points
- Structures can be passed to functions
- Structures can be returned from functions
- Pointer/reference improves efficiency
- Structures can contain member functions
- Dot (.) and arrow (->) operators are used
Arrays of Structures in C++
An array of structures in C++ is a collection of structure variables of the same structure type, stored contiguously in memory. It is used when we need to handle multiple records of the same type (e.g., many students, employees, books).
1. Declaration of Array of Structures
Syntax
struct Student {
int roll;
char name[20];
float marks;
};
Student s[3];
✔ s is an array containing 3 Student structures.
2. Initialization of Array of Structures
Method 1: At Compile Time
Student s[2] = {
{101, "Amit", 85.5},
{102, "Neha", 90.0}
};
Method 2: Runtime Initialization
for(int i = 0; i < 2; i++) {
cin >> s[i].roll >> s[i].marks;
}
3. Accessing Structure Members in Array
Use array index + dot operator.
cout << s[0].name;
cout << s[1].marks;
4. Example Program (Exam-Oriented)
#include <iostream>
using namespace std;
struct Student {
int roll;
float marks;
};
int main() {
Student s[3];
for(int i = 0; i < 3; i++) {
s[i].roll = i + 1;
s[i].marks = 80 + i;
}
for(int i = 0; i < 3; i++) {
cout << s[i].roll << " " << s[i].marks << endl;
}
return 0;
}
5. Passing Array of Structures to Function
void display(Student s[], int n) {
for(int i = 0; i < n; i++)
cout << s[i].roll << " " << s[i].marks << endl;
}
Call:
display(s, 3);
6. Using Pointer with Array of Structures
Student *p = s;
cout << p->roll; // same as s[0].roll
cout << (p + 1)->marks; // s[1].marks
7. Sorting Array of Structures (Example)
for(int i = 0; i < n - 1; i++) {
for(int j = i + 1; j < n; j++) {
if(s[i].marks < s[j].marks) {
Student temp = s[i];
s[i] = s[j];
s[j] = temp;
}
}
}
8. Advantages
- Organizes large amounts of related data
- Easy data processing (searching, sorting)
- Efficient memory usage
9. Key Exam Points
- Array of structures stores multiple records
- Access using array[index].member
- Can be passed to functions
- Can be accessed using pointers
- Used in real-world data management
Arrays within a Structure in c++
In C++, arrays can be declared as members of a structure. This allows us to store multiple values of the same type inside a single structure variable.
1. Declaring an Array Inside a Structure
Syntax:
struct StructureName {
dataType arrayName[size];
};
Example:
#include <iostream>
using namespace std;
struct Student {
int marks[5]; // Array inside structure
};
int main() {
Student s1;
// Assigning values
for(int i = 0; i < 5; i++) {
s1.marks[i] = (i + 1) * 10;
}
// Displaying values
for(int i = 0; i < 5; i++) {
cout << "Marks " << i+1 << ": " << s1.marks[i] << endl;
}
return 0;
}
Output:
Marks 1: 10
Marks 2: 20
Marks 3: 30
Marks 4: 40
Marks 5: 50
2. Structure with Multiple Members Including Array
#include <iostream>
using namespace std;
struct Student {
int rollNo;
char name[20];
float marks[3];
};
int main() {
Student s;
s.rollNo = 101;
cout << "Enter name: ";
cin >> s.name;
cout << "Enter 3 subject marks:\n";
for(int i = 0; i < 3; i++) {
cin >> s.marks[i];
}
cout << "\nStudent Details:\n";
cout << "Roll No: " << s.rollNo << endl;
cout << "Name: " << s.name << endl;
cout << "Marks: ";
for(int i = 0; i < 3; i++) {
cout << s.marks[i] << " ";
}
return 0;
}
3. Array of Structures (Each Structure Contains an Array)
#include <iostream>
using namespace std;
struct Student {
int roll;
int marks[3];
};
int main() {
Student s[2]; // Array of structures
for(int i = 0; i < 2; i++) {
cout << "Enter roll number: ";
cin >> s[i].roll;
cout << "Enter 3 marks:\n";
for(int j = 0; j < 3; j++) {
cin >> s[i].marks[j];
}
}
cout << "\nStudent Details:\n";
for(int i = 0; i < 2; i++) {
cout << "Roll: " << s[i].roll << " Marks: ";
for(int j = 0; j < 3; j++) {
cout << s[i].marks[j] << " ";
}
cout << endl;
}
return 0;
}
4. Important Points
- Arrays inside structures work like normal arrays.
- Access format:
- structureVariable.arrayName[index]
- Size of array must be fixed at compile time (unless using dynamic memory).
- Memory for array is allocated inside the structure.
5. Structure with Multidimensional Array
struct Matrix {
int arr[2][2];
};
Access example:
m.arr[0][1] = 10;
Summary
- A structure can contain one or more arrays.
- Arrays help store multiple related values in a single structure.
- Useful in student records, employee data, matrices, etc.
- Can combine:
- Array inside structure
- Array of structures
- Multidimensional arrays inside structures
Structures within a Structure (Nested Structure) in C++
A Nested Structure means a structure defined inside another structure or a structure used as a member of another structure. It helps organize related data in a hierarchical way.
1. Defining Structure Inside Another Structure
Syntax:
struct Outer {
dataType member1;
struct Inner {
dataType member2;
} innerObject;
};
2. Example: Student with Date of Birth
#include <iostream>
using namespace std;
struct Date
{
int day;
int month;
int year;
};
struct Student {
int rollNo;
string name;
Date dob; // Nested structure
};
int main() {
Student s1;
s1.rollNo = 101;
s1.name = "Rahul";
s1.dob.day = 15;
s1.dob.month = 8;
s1.dob.year = 2005;
cout << "Roll No: " << s1.rollNo << endl;
cout << "Name: " << s1.name << endl;
cout << "Date of Birth: "
<< s1.dob.day << "/"
<< s1.dob.month << "/"
<< s1.dob.year << endl;
return 0;
}
Output:
Roll No: 101
Name: Rahul
Date of Birth: 15/8/2005
3. Structure Defined Completely Inside Another Structure
#include <iostream>
using namespace std;
struct Employee {
int empId;
string name;
struct Salary {
float basic;
float bonus;
} sal;
};
int main() {
Employee e1;
e1.empId = 1;
e1.name = "Amit";
e1.sal.basic = 30000;
e1.sal.bonus = 5000;
cout << "Employee ID: " << e1.empId << endl;
cout << "Name: " << e1.name << endl;
cout << "Total Salary: "
<< e1.sal.basic + e1.sal.bonus << endl;
return 0;
}
4. Array of Nested Structures
struct Date {
int d, m, y;
};
struct Student {
int roll;
Date dob;
};
Student s[2];
s[0].roll = 1;
s[0].dob.d = 10;
5. Accessing Nested Structure Members
- General format:
- outerStructure.innerStructure.member
Example:
s1.dob.year
e1.sal.basic
6. Why Use Nested Structures?
- Better data organization
- Logical grouping of related data
- Improves readability
- Useful in real-world applications (Employee, Address, Bank Account, etc.)
7. Memory Concept
- Memory is allocated for all members of outer and inner structures.
- Inner structure variables occupy memory inside the outer structure.
Pointers and Structures in C++
In C++, a pointer can store the address of a structure variable. This is useful for dynamic memory allocation, passing structures to functions, and efficient data handling.
1. Declaring a Pointer to a Structure
Syntax:
struct StructureName {
dataType member;
};
StructureName *ptr;
Example:
#include <iostream>
using namespace std;
struct Student {
int roll;
float marks;
};
int main() {
Student s1 = {101, 85.5};
Student *ptr; // Pointer to structure
ptr = &s1; // Store address of s1
cout << "Roll: " << ptr->roll << endl;
cout << "Marks: " << ptr->marks << endl;
return 0;
}
2. Accessing Members Using Pointer
There are two ways:
✔ Using (*pointer).member
cout << (*ptr).roll;
✔ Using Arrow Operator -> (Recommended)
cout << ptr->roll;
👉 ptr->roll is equal to (*ptr).roll
3. Dynamic Memory Allocation for Structure
Using new operator:
#include <iostream>
using namespace std;
struct Employee {
int id;
float salary;
};
int main() {
Employee *emp = new Employee;
emp->id = 1;
emp->salary = 50000;
cout << "ID: " << emp->id << endl;
cout << "Salary: " << emp->salary << endl;
delete emp; // Free memory
return 0;
}
4. Pointer to Structure with Array
#include <iostream>
using namespace std;
struct Student {
int roll;
int marks[3];
};
int main() {
Student s = {101, {80, 85, 90}};
Student *ptr = &s;
cout << "Roll: " << ptr->roll << endl;
for(int i = 0; i < 3; i++) {
cout << "Marks: " << ptr->marks[i] << endl;
}
return 0;
}
5. Array of Structure Pointers
Student s1 = {1, 80};
Student s2 = {2, 90};
Student *ptr[2]; // Array of structure pointers
ptr[0] = &s1;
ptr[1] = &s2;
cout << ptr[0]->roll;
6. Passing Structure Pointer to Function
#include <iostream>
using namespace std;
struct Student {
int roll;
};
void display(Student *ptr) {
cout << "Roll: " << ptr->roll << endl;
}
int main() {
Student s1 = {101};
display(&s1);
return 0;
}
7. Important Points
- Use -> operator to access members through pointer.
- (*ptr).member and ptr->member are equivalent.
- Dynamic allocation requires delete.
- Passing structure pointer is more efficient than passing whole structure.

0 comments
Post a Comment