Professional Documents
Culture Documents
PPS Unit-5-Structures
PPS Unit-5-Structures
Structure is a user defined data type which allows you to combine data items of different
data-types under a single name.
Structures are used to represent a record.
E.g. To keep track of books in a library, we will create a structure “book”, which will contain
following attributes:
- Title
- Author
- Subject
- BookID
Syntax of a structure:
struct [structure tag]
{
member definition;
member definition;
...
member definition;
} [one or more structure variables];
NOTE: When a structure is created, no memory is allocated. Memory only gets allocated when
we declare the structure variable, also called the instance of a structure.
Example:
struct Person
{
char name[50];
int age;
float salary;
}p1;
// Here “p1” is the structure variable. When the structure variable is created, the memory will
be allocated.
In the above example, the memory allocated to p1 will be?
Ans: 50*1 + 4*1 + 4*1 = 58 bytes
Accessing structure variables:
To access any member of a structure, we use the member access operator (.). The member
access operator is coded as a period between the structure variable name and the structure
member that we wish to access. You would use struct keyword to define variables of structure
type.
E.g.
bill.age = 50;
Example of a structure:
#include <iostream>
using namespace std;
struct Person
{
char name[50];
int age;
float salary;
}p1;
int main()
{
//Person p1;
return 0;
}
Output:
Enter Full name: Ankita Singh
Enter age: 27
Enter salary: 90000
Displaying Information.
Name: Ankita Singh
Age: 27
Salary: 90000
struct Person
{
char name[50];
int age;
float salary;
};
int main()
{
Person p;
return 0;
}
void displayData(Person p)
{
cout << "\nDisplaying Information." << endl;
cout << "Name: " << p.name << endl;
cout <<"Age: " << p.age << endl;
cout << "Salary: " << p.salary;
}
Output:
Displaying Information.
Name: Ankita Singh
Age: 27
Salary: 90000
displayData(p);
Pointers to Structures
Member variables of a structure can also be accessed using pointers that point to the structure
variables.
Example:
struct Distance
{
int feet;
float inch;
};
int main()
{
Distance *ptr, d;
ptr = &d;
return 0;
}
Output:
Enter feet: 4
Enter inch: 6
Displaying information.
Distance = 4 feet 6 inches
NOTE: In the above program, pointer variable ‘ptr’ and structure variable ‘d’ are of type
structure ‘Distance’.
However, when we are accessing using pointers, then operator is better than the dot(.)
operator as its higher in the hierarchy of operators.
ptr->feet is same as (*ptr).feet
ptr->inch is same as (*ptr).inc