Arrays allow to define type of variables that can hold several data items of
the same kind.
Similarly structure is another user defined data type available in C that
allows to combine data items of different kinds.
Structures are used to represent a record. Suppose you want to keep track
of your books in a library. You might want to track the following attributes
about each book −
Title
Author
Subject
Book ID
Defining a Structure
To define a structure, the struct
keyword is used.
Syntax of struct
struct structureName
{
dataType member1;
dataType member2;
...
};
Here is an example:
struct Person
{
char name[50];
int citNo;
float salary;
};
Here, a derived type struct Person
is defined. Now, you can create
variables of this type.
Memory Representation Of structure
struct employee
{ int id;
char name[10];
float salary;
};
Create struct variables
struct Person
{
char name[50];
int citNo;
float salary;
};
int main()
{
struct Person person1, person2, p[20];
return 0;
}
Another way of creating a struct
variable is:
struct Person
{
char name[50];
int citNo;
float salary;
} person1, person2, p[20];
In both cases, two variables person1,
person2, and an array variable p
having 20 elements of type struct
Person are created.
Access members of a structure
There are two types of operators used for accessing members of a structure.
. - Member operator
🡪 - Structure pointer operator (will be discussed in the next tutorial)
Suppose, you want to access the salary of person2. Here's how you can do
it.
person2.salary
How to access data members of a structure using a
struct variable?
Syntax:
var_name.member1_name;
var_name.member2_name;
Example:
struct StudentData
{
char *stu_name;
int stu_id;
int stu_age;
};
struct StudentData student;
student.stu_name = "Steve";
student.stu_id = 1234;
student.stu_age = 30;
Output:
Student Name is: Steve
Student Id is: 1234
Student Age is: 30
include <stdio.h>
struct StudentData
{
char *stu_name;
int stu_id;
int stu_age;
};
int main()
{
struct StudentData student;
student.stu_name = "Steve";
student.stu_id = 1234;
student.stu_age = 30;
printf("Student Name is: %s", student.stu_name);
printf("\nStudent Id is: %d", student.stu_id);
printf("\nStudent Age is: %d", student.stu_age);
return 0;
}
How to Copy Structure Variables?
Two variables of the same structure type can be copied the same way as
ordinary variables.
If persona1 and person2 belong to the same structure, then the following
statements Are valid.
person1 = person2;
person2 = person1;
How to Compare Structure Variables?
C does not permit any logical operators on structure variables
In case, we need to compare them, we may do so by comparing members
individually.
person1 = = person2
person1 ! = person2
Statements are not permitted.
Program for comparison of structure variables
struct class
{
int no;
char name [20];
float marks;
}
main ( )
{
int x;
struct class stu1 = { 111, “Rao”, 72.50};
struct class stu2 = {222, “Reddy”, 67.80};
struct class stu3;
stu3 = stu2;
x = ( ( stu3.no= = stu2.no) && ( stu3.marks = = stu2.marks))?1:0;
if ( x==1)
{
printf (“ \n student 2 & student 3 are same \n”);
printf (“%d\t%s\t%f “ stu3.no, stu3.name, stu3.marks);
}
else
printf ( “\n student 2 and student 3 are different “);
}
Out Put:
Student 2 and student 3 are same
222 reddy 67.0000
An array of structures in C can
be defined as the collection of
multiple structures variables
where each variable contains
information about different
entities.
The array of structures in C are
used to store information about
multiple entities of different
data types.
The array of structures is also
known as the collection of
structures.
#include<stdio.h>
struct student
{
int rollno;
char name[10];
};
int main()
{
int i;
struct student st[5];
printf("Enter Records of 5 students");
for(i=0;i<5;i++)
{
printf("\nEnter Rollno:");
scanf("%d",&st[i].rollno);
printf("\nEnter Name:");
scanf("%s",&st[i].name);
}
printf("\nStudent Information List:");
for(i=0;i<5;i++)
{
printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);
}
}
Output:
Enter Records of 3 students
Enter Rollno:1
Enter Name:Sonoo
Enter Rollno:2
Enter Name:Ratan
Enter Rollno:3
Enter Name:Vimal
Student Information List:
Rollno:1, Name:Sonoo
Rollno:2, Name:Ratan
Rollno:3, Name:Vimal
Nested Structure in C
C provides us the feature of nesting one structure within another
structure by using which, complex data types are created.
For example, we may need to store the address of an entity
employee in a structure. The attribute address may also have the
subparts as street number, city, state, and pin code.
Hence, to store the address of the employee, we need to store the
address of the employee into a separate structure and nest the
structure address into the structure employee.
Consider the following program.
#include<stdio.h>
struct address {
char city[20];
int pin;
char phone[14];
};
struct employee {
char name[20];
struct address add;
};
void main ()
{
struct employee emp;
printf("Enter employee Name,City,Pincode,Phone information?\n");
scanf("%s %s %d %s",emp.name,emp.add.city, &emp.add.pin, emp.add.phone);
printf("Printing the employee information....\n");
printf("name: %s\nCity: %s\nPincode: %d\nPhone:%s”,
emp.name,emp.add.city,emp.add.pin,emp.add.phone);
}
Output
Enter employee Name, City, Pincode,
Phone information
Arun
Delhi
110001
1234567890
Printing the employee information....
name: Arun
City: Delhi
Pincode: 110001
Phone: 1234567890
Pointers to structures in C
It is defined as the pointer which points to the address of the
memory block that stores a structure is known as the structure
pointer.
We have already learned that a pointer is a variable which
points to the address of another variable of any data type like
int, char, float etc.
Similarly, we can have a pointer to structures, where a pointer
variable can point to the address of a structure variable. Here is
how we can declare a pointer to a structure variable.
How to declare Pointer to Struct Variable
struct dog
{
char name[10];
char breed[10];
int age;
char color[10];
};
struct dog spike;
// declare the struct variable
struct dog *ptr_dog // declaring a pointer to a structure of type struct dog
#include<stdio.h>
struct student{
int sno;
char sname[30];
float marks;
};
main ( ){
struct student s;
struct student *st;
printf("enter sno, sname, marks:");
scanf ("%d%s%f", & s.sno, s.sname, &s. marks);
st = &s;
printf ("details of the student are");
printf ("Number = %d\n", st ->sno);
printf ("name = %s\n", st->sname);
printf ("marks =%f\n", st ->marks);
}
Output
Let us run the above program
that will produce the following
result −
enter sno, sname, marks:1
Lucky 98
details of the student are:
Number = 1
name = Lucky
marks =98.000000
Passing the Structure to Function
Passing of structure to the function can be done in two ways:
By passing all the elements to the function individually.
By passing the entire structure to the function.
entire structure is passed to the function. This can be done using call by
reference as well as call by value method.
Passing Structure Members as arguments to Function
#include<stdio.h>
struct student
{
char name[20];
int roll_no;
int marks;
};
void print_struct(char name[ ], int roll_no, int marks);
int main()
{
struct student stu = {"Tim", 1, 78};
print_struct(stu.name, stu.roll_no, stu.marks);
}
void print_struct(char name[], int roll_no, int marks)
{
printf("Name: %s\n", name);
printf("Roll no: %d\n", roll_no);
printf("Marks: %d\n", marks);
printf("\n");
}
Output:
Name: Tim
Roll no: 1
Marks: 78
By passing the entire structure to the function
#include <stdio.h>
struct student
{
char name[50];
int age;
};
void display(struct student s);
int main() {
struct student s1;
printf("Enter name: ");
scanf("%s", s1.name);
printf("Enter age: ");
scanf("%d", &s1.age);
display(s1); // passing struct as an argument
return 0;
}
void display(struct student s)
{
printf("\nDisplaying information\n");
printf("Name: %s", s.name);
printf("\nAge: %d", s.age);
}
Output
Enter name: Ankit
Enter age: 13
Displaying information
Name: Ankit
Age: 13
C Unions
Unions are conceptually similar to structures.
The syntax to declare/define a union is also similar to that of a
structure.
The only differences is in terms of storage.
In structure each member has its own storage location,
whereas all members of union uses a single shared memory
location which is equal to the size of its largest data member.
This implies that
although a union
may contain many
members of
different types,
it cannot handle all
the members at the
same time.
A union is declared
using the union
keyword.
Accessing a Union Member in C
Syntax for accessing any union member is
similar to accessing structure members,
union test
{
int a;
float b;
char c;
}t;
t.a; //to access members of union t
t.b;
t.c;
union item
{
int m;
float x;
char c;
}It1;
In the union declared above the member
x requires 4 bytes which is largest
amongst the members for a 16-bit
machine.
Other members of union will share the
same memory address.
References for MCQ on Structure & Union
https://www.javatpoint.com/test/c-structure-union-enums-1
https://www.geeksforgeeks.org/c-language-2-gq/structure-union-gq/
https://letsfindcourse.com/technical-questions/c/structure-union
https://www.examtray.com/c-questions/c-mcq-questions-and-answer
s-structures-and-pointers-1
https://www.sanfoundry.com/c-programming-questions-and-answers-
structures-functions/
Multiple Choice Question -
Structure And Union
#include‹stdio.h›
int main()
{
struct site
{
char name[] = "GeeksQuiz";
int no_of_pages = 200;
};
struct site *ptr;
printf("%d ", ptr->no_of_pages);
printf("%s", ptr->name);
getchar();
return 0;
}
(A) 200 GeeksQuiz
(B) 200
(C) Runtime Error
(D) Compiler Error
Answer: (D) Compiler Error
Explanation: When we declare a
structure or union, we actually
declare a new data type suitable
for our purpose.
So we cannot initialize values as
it is not a variable declaration but
a data type declaration.
Example:
struct student s;
struct student *st;
st = &s;
Answer: (C) Compiler Error
Explanation:
In C, struct and union types cannot
have static members.
In C++, struct types are allowed to
have static members,
but union cannot have static
members in C++ also.
#include<stdio.h>
struct st
{
int x;
static int y;
};
int main()
{
printf("%d", sizeof(struct st));
return 0;
}
(A) 4
(B) 8
(C) Compiler Error
(D) Runtime Error
Answer: (C) 18 bytes
Explanation: Short array s[5] will
take 10 bytes as size of short is 2
bytes.
When we declare a union, memory
allocated for the union is equal to
memory needed for the largest
member of it, and all members share
this same memory space.
Since u is a union, memory allocated
to u will be max of float y(4 bytes)
and long z(8 bytes). So, total size
will be 18 bytes (10 + 8).
struct {
short s[5];
union {
float y;
long z;
}u;
} t;
Assume that objects of the type short,
float and long occupy 2 bytes, 4 bytes
and 8 bytes, respectively. The memory
requirement for variable t, ignoring
alignment considerations, is (GATE CS
2000)
(A) 22 bytes
(B) 14 bytes
(C) 18 bytes
(D) 10 bytes
Which of the following operators can be
applied on structure variables?
(A) Equality comparison ( == )
(B) Assignment ( = )
(C) Both of the above
(D) None of the above
Answer: (B)
Explanation: A structure variable can be
assigned to other using =, but cannot be
compared with other using ==
1. Which of the following are
themselves a collection of different
data types?
A. String
B. Structures
C. Char
D. None of the above
View Answer
Ans : B
Explanation: A structure is a user
defined data type in C/C++. A
structure creates a data type that
can be used to group items of
possibly different types into a
single type.
0 Comments