Structures
The Type Definition(typedef), Structure Type
declaration, Initialization, Accessing Structures,
Operations on Structures, Complex Structures
typedef
It’s a keyword used to create new name for an already
existing data type.
Eg : typedef int marks;
typedef float amount
marks m1, m2, m3;
amount a1, a2, a3;
m1, m2,m3 will be of type int
a1, a2, a3 will be of type float
typedef
typedef should be specified before any of the function
prototypes and function definition(beginning of the
program).
#include<stdio.h>
typedef float amount;
typedef float time;
typedef float rate;
int main()
{
amount p,si;
time t;
rate r;
printf(" enter p,t,r\n");
scanf("%f%f%f",&p,&t,&r);
si=(p*t*r)/100;
printf(" SI is %f\n",si);
}
Introduction to Structures
• Structure is a collection of variables of
different types under single name.
• For example: You want to store some
information about a person: his/her name,
salary. You can easily create variables
different
name, salary to store information
• separately.
Instead of using different variables we can
create structure person which contains all the
details about the person.
• A structure is same as that of records. It stores related
information about an entity.
• Structure is basically a user defined data type that
can store related information (even of different data
types) together.
• A structure is declared using the keyword struct
followed by a structure name. All the variables of the
structures are declared within the structure. A
structure type is defined by using the given syntax.
• struct struct-name
{ data_type var-name;
data_type var-name;
...
};
struct student
{ int r_no;
char name[20];
char course[20];
float fees;
};
• The structure definition does not allocate any
memory. It just gives a template that conveys to the
C compiler how the structure is laid out in memory
and gives details of the member names. Memory is
allocated for the structure when we declare a
variable of the structure. For ex, we can define a
variable of student by writing
struct student stud1;
typedef declarations
• When we precede a struct name with typedef
keyword, then the struct becomes a new type. It is
used to make the construct shorter with more
meaningful names for types already defined by C or
for types that you have declared. With a typedef
declaration, becomes a synonym for the type.
• For example, writing
typedef struct student
{
int r_no;
char name[20];
char course[20];
float fees;
};
Now that you have preceded the structure’s name with
the keyword typedef, the student becomes a new data
type. Therefore, now you can straight away declare
variables of this new data type as you declare variables
of type int, float, char, double, etc. to declare a variable
of structure student you will just write,
student stud1;
Initialization of Structures
• Initializing a structure means assigning some
constants to the members of the structure.
• When the user does not explicitly initialize the
structure then C automatically does that. For int and
float members, the values are initialized to zero and
char and string members are initialized to the ‘\0’ by
default.
• The initializers are enclosed in braces and are
separated by commas. Note that initializers match
their corresponding types in the structure definition.
The general syntax to initialize a structure
variable is given as follows.
struct struct_name
{ data_type member_name1;
data_type member_name2;
data_type member_name3;
.......................................
}struct_var = {constant1, constant2,
constant 3,...};
OR
struct struct_name
{ data_type member_name1;
data_type member_name2;
data_type member_name3;
.......................................
};
struct struct_name struct_var = {constant1,
constant2, ….};
struct student stud1 = {01, “Rahul”, “BCA”,
45000};
Accessing Members of the
• Each member of aStructure
structure can be used just like a
normal variable, but its name will be a bit longer. A
structure member variable is generally accessed
using a ‘.’ (dot operator).
• The syntax of accessing a structure a member of a
structure is:
struct_var.member_name
• For ex, to assign value to the individual data
members of the structure variable Rahul, we may
write,
stud1.r_no = 01;
strcpy(stud1.name, “Rahul”);
stud1.course = “BCA”;
stud1.fees = 45000;
• We can assign a structure to another structure of the
same type. For ex, if we have two structure variables
stu1 and stud2 of type struct student given as
• struct student stud1 = {01, "Rahul", "BCA", 45000};
• struct student stud2;
• Then to assign one structure variable to another we
will write, stud2 = stud1;
Operations on structures
In C, the only operation that can be applied to
struct variables is assignment
#include <stdio.h>
struct Point {
int x;
int y;
};
int main()
{
struct Point p1 = {10, 20};
struct Point p2 = p1; // works: contents of p1 are
copied to p2
printf(" p2.x = %d, p2.y = %d", p2.x, p2.y);
return 0;
}
Complex Structures
In C programming, complex structures typically refer
to structures (structs) that contain:
• Nested structures (structures within structures)
• Pointers to structures
• Self-referential structures (important in linked
lists, trees, etc.)
• Structures with dynamic memory
• Arrays inside structures
Complex Structures
1.Nested Structures: Structure inside another
Structure.
struct DOB
{
int day;
int month;
int year;
};
struct student
{ int roll_no;
char name[100];
float fees;
struct DOB date;
};
Complex Structures
#include<stdio.h>
int main()
{ struct DOB
{
int day;
int month;
int year;
};
struct student
{ int roll_no;
char name[100];
float fees;
struct DOB date;
};
struct student stud1;
Complex Structures
printf(“\n Enter the roll number : “);
scanf(“%d”, &stud1.roll_no);
printf(“\n Enter the name : “);
scanf(“%s”, stud1.name);
printf(“\n Enter the fees : “);
scanf(“%f”, &stud1.fees);
printf(“\n Enter the DOB : “);
scanf(“%d %d %d”, &stud1.date.day,
&stud1.date.month, &stud1.date.year);
printf(“\n ********STUDENT’S DETAILS *******”);
printf(“\n ROLL No. = %d”, stud1.roll_no);
printf(“\n NAME. = %s”, stud1.name);
printf(“\n FEES. = %f”, stud1.fees);
printf(“\n DOB = %d - %d - %d”, stud1.date.day,
stud1.date.month, stud1.date.year);
}
Complex Structures
2.Pointers to structures: Using pointers to access and
manipulate structures dynamically.
#include <stdio.h>
#include <stdlib.h>
struct Student {
char name[50];
int roll;
};
int main() {
struct Student *ptr = (struct Student
*)malloc(sizeof(struct Student));
ptr->roll = 101;
strcpy(ptr->name, "Alice");
printf("Name: %s, Roll: %d\n", ptr->name, ptr->roll);
free(ptr); }
Complex Structures
3. Self referential structures : those structures that
contain a reference to data of its same type. That is, a
self-referential structure in addition to other data
contains a pointer to a data that is of the same type as
that of the structure. For example, consider the structure
node given below.
struct node
{
int val;
struct node *next;
};
Here the structure node will contain two types of data an
integer val and next that is a pointer to a node. You must
be wondering why do we need such a structure?
Actually, self-referential structure is the foundation of
other data structures.
Union
• Like structure, a union is a collection of variables of
different data types. The only difference between a
structure and a union is that in case of unions, you
can only store information in one field at any one
time.
• To better understand union, think of it as a chunk of
memory that is used to store variables of different
types. When a new value is assigned to a field, the
existing data is replaced with the new data.
• Thus unions are used to save memory. They are
useful for applications that involve multiple
members, where values need not be assigned to all
DECLARING A UNION
The syntax for declaring a union is same as that of
declaring a structure.
union union-name
{ data_type var-name;
data_type var-name;
...
};
Again, the typedef keyword can be used to simplify the
declaration of union variables.
• The most important thing to remember about a union is
that the size of a union is the size of its largest field.
This is because a sufficient number of bytes must be
ACCESSING A MEMBER OF A UNION
• A member of a union can be accessed using the same
syntax as that of a structure. To access the fields of a
union, use the dot operator(.). That is the union
variable name followed by the dot operator followed by
the member name.
INITIALIZING UNIONS
• It is an error to initialize any other union member
except the first member
• A striking difference between a structure and a union is
that in case of a union, the field fields share the same
memory space, so fresh data replaces any existing
data. Look at the code given below and observe the
difference between a structure and union when their
fields are to be initialized.
#include<stdio.h>
typedef struct POINT1
{ int x, y;
};
typedef union POINT2
{
int x;
int y;
};
main()
{ POINT1 P1 = {2,3};
// POINT2 P2 ={4,5}; Illegeal with union
POINT2 P2;
P2. x = 4;
P2.y = 5;
printf("\n The co-ordinates of P1 are %d and %d",
P1.x, P1.y);
printf("\n The co-ordinates of P2 are %d and %d",
P2.x, P2.y); return 0; }
Pointers
A pointer is a reference to another variable
(memory location) in a program
– Used to change variables inside a function
(reference parameters)
– Used to remember a particular member of a group
(such as an array)
– Used in dynamic (on-the-fly) memory allocation
(especially of arrays)
– Used in building complex data structures (linked
lists, stacks, queues, trees, etc.)
Outline
Pointer Constants, Pointer Values, Pointer variables,
Accessing Variables through Pointers, Pointer
Declaration and Definition, Declaration Vs
Redirection, Initialization of pointer Variables
Pointer Basics
Variables are allocated at addresses in computer
memory (address depends on
computer/operating system)
Name of the variable is a reference to that
memory address
A pointer variable contains a representation of
an address of another variable (P is a pointer
variable in the following):
Name V P
Address v (some value) p (some value)
int V = 101;
Abstract
101
Representation
int *P = &V;
Concrete 4 bytes for 4 bytes for
Representation int value 101 mem address v
Pointer Variable Definition
Address (&) Operator
Pointer Variable Initialization/Assignment
NULL - pointer lit constant to non-existent address
– used to indicate pointer points to nothing
Can initialize/assign pointer vars to NULL or use the
address (&) op to get address of a variable
– variable in the address operator must be of the right
type for the pointer (an integer pointer points only at
integer variables)
Examples:
int V;
int *P = &V;
int A[5];
P = &(A[2]);
Indirection (*) Operator
A pointer variable contains a memory address
To refer to the contents of the variable that
the pointer points to, we use indirection
operator
Syntax: *PointerVariable
Example:
int V = 101;
int *P = &V;
/* Then *P would refer to the contents of the
variable V (in this case, the integer 101) */
printf(“%d”,*P); /* Prints 101 */
Pointer Sample
Pointer Constant and
Values
In constant pointers, the pointer points to a
fixed memory location, and the value at that
location can be changed because it is a
variable, but the pointer will always point to
the same location.
Syntax to declare pointer constant
datatype *const variable_name=address;
#include<stdio.h>
int main()
{
int a=10,b=10;
int *const p1=&a;
printf(" Content of a is %d\n",*p1);
printf(" Content of p1 is %p\n",p1);
p1=&b; //not allowed because p1 is read -
only
}
Once address is allocated to pointer variable
we can’t change later, but we can change
the value to which a pointer variable is
pointing to.
#include<stdio.h>
int main()
{
int a=10,b=10;
int *const p1=&a;
printf(" Content of a is %d\n",*p1);
printf(" Content of p1 is %p\n",p1);
//p1=&b; //not allowed because p1 is read -
only
*p1=90;
printf(" Content of a is %d\n",*p1);
}
End