Chapter 9
structures

What is a Structure ?
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
Syntax for creating structures
struct hytek{
int like;
float subscriber;
char username[20];
// this declares a new user defined data-type
}
we use this datatype like this
CODE ***
struct hytek u1;
strcpy(u1.subscriber,”kuldeep sharma”);
u1.like = 1;
u1.subscriber = 10.2;
so a structures in c is a collection of variables of different types under a single name.
why use structures ?
We can create the data types in the Hi-Tech structure separately but when the number of properties in a structure increases it becomes difficult for us to create data variables without structures in a nut shell.
a) structures keep the data organised
b) structures make data management easy for the programmer
Array of Structures in C
Just like in a Array of integers and Array of floats and array of characters we can create an Array of structures
struct employee hytek [50]; // an array of structures
We can access the data using
hytek [0]. code = 1000;
hytek [1]. code = 1001; // and so on……
Initializing Structures
Structures can also be initialised as follows :::
struct employee Kuldeep = {1000,72.342,"Kuldeep sharma" };
struct employee happy = {1001,72.346,"happy sharma" };
struct employee ashish={0};//all elements set to 0
Structures in memory
Structures are stored in contiguous memory locations for the structure u1 of type struct hytek memory layout looks like this

In an array of structures these users data are stored adjacent to each other
Pointer to Structures
A pointer to structure can be created as follows
struct employee *ptr;
ptr = &e1;
Now we can print structure elements
printf(“%d”,*(ptr).code);
Arrow Operator
Instead of writing*(ptr).code, we can use Arrow operator to access structure properties as follows
*(ptr).code or ptr-> code
Here -> is known as the arrow operator
Passing Structures to a Function
A structure can be passed to a function just like any other data type
void show(struct employee e); //function prototype
Typedef keyword
We can use the typedef keyword to create an additional name for data type in C typedef is more commonly used with structures
#include <stdio.h >>
int main()
{
typedef unsigned int unit;
unit i,j;
i=10;
j=20;
printf("Value of i is :%d",i);
printf("\nValue of j is :%d",j);
return 0;
}