You are on page 1of 52

Structures

1
What is a Structure?
 Used for handling a group of logically
related data items
 Examples:
 Student name, roll number, and marks
 Real part and complex part of a complex number

 Helps in organizing complex data in a more


meaningful way
 The individual structure elements are called
members
2
Defining a Structure
struct tag {
member 1;
member 2;
:
member m;
};

 struct is the required C keyword


 tag is the name of the structure
 member 1, member 2, … are individual member
declarations

3
Contd.
 The individual members can be ordinary variables,
pointers, arrays, or other structures (any data type)
 The member names within a particular structure
must be distinct from one another
 A member name can be the same as the name of
a variable defined outside of the structure
 Once a structure has been defined, the individual
structure-type variables can be declared as:
struct tag var_1, var_2, …, var_n;

4
Example
 A structure definition
struct student {
char name[30];
int roll_number;
int total_marks;
char dob[10];
};

 Defining structure variables:


struct student a1, a2, a3;

A new data-type
5
A Compact Form
 It is possible to combine the declaration of the structure
with that of the structure variables:

struct tag {
member 1;
member 2;
:
member m;
} var_1, var_2,…, var_n;

 Declares three variables of type struct tag


 In this form, tag is optional

6
Accessing a Structure
 The members of a structure are processed
individually, as separate entities
 Each member is a separate variable
 A structure member can be accessed by writing
variable.member
where variable refers to the name of a structure-type
variable, and member refers to the name of a
member within the structure
 Examples:
a1.name, a2.name, a1.roll_number, a3.dob

7
Arrays of Structures
 Once a structure has been defined, we can
declare an array of structures
struct student class[50];

type name

 The individual members can be accessed as:


class[i].name
class[5].roll_number

8
Arrays within Structures
 A structure member can be an array
struct student
{
char name[30];
int roll_number;
int marks[5];
char dob[10];
} a1, a2, a3;
 The array element within the structure can be
accessed as:
a1.marks[2], a1.dob[3],…
9
Structure Initialization
 Structure variables may be initialized following
similar rules of an array. The values are provided
within the second braces separated by commas
 An example:
struct complex a={1.0,2.0}, b={-3.0,4.0};

a.real=1.0; a.imag=2.0;
b.real=-3.0; b.imag=4.0;
10
Operations on Structure
Variables
 Unlike arrays, a structure variable can be directly
assigned to another structure variable of the same type
a1 = a2;
 All the individual members get assigned

 Two structure variables can not be compared for


equality or inequality
if (a1 == a2)…… this cannot be done

11
Example: Complex number addition
void main()
{
struct complex
{
float real;
float cmplex;
} a, b, c;

scanf (“%f %f”, &a.real, &a.cmplex);


scanf (“%f %f”, &b.real, &b.cmplex);

c.real = a.real + b.real;


c.cmplex = a.cmplex + b.cmplex;
printf (“\n %f + %f j”, c.real, c.cmplex);
}
12
Nested structures

• Nested structure in C is, a structure within structure. One structure can be


declared inside other structure as we declare structure members inside a
structure.

• The structure variables can be a normal structure variable or a pointer


variable to access the data. You can learn below concepts in this section.

13
Programming example structure within structure In C Using normal variable

14
Structure within structure (Nested Structure In C ) using pointer variable:

15
Parameter Passing in a
Function
 Structure variables can be passed as parameters like
any other variables. Only the values will be copied
during function invocation

void swap (struct complex a, struct complex b)


{
struct complex tmp;

tmp=a;
a=b;
b=tmp;
} 16
Returning structures
 It is also possible to return structure values from a
function. The return data type of the function should
be as same as the data type of the structure itself
struct complex add(struct complex a, struct complex b)
{
struct complex tmp;

tmp.real = a.real + b.real;


tmp.imag = a.imag + b.imag;
return(tmp);
}

Direct arithmetic operations are not possible with structure variables


17
Passing structures to functions

 A structure can be passed to any function from main function or from any sub
function.
 Structure definition will be available within the function only.
 It won’t be available to other functions unless it is passed to those functions by
value or by address(reference).
 Else, we have to declare structure variable as global variable. That means,
structure variable should be declared outside the main function. So, this
structure will be visible to all the functions in a C program.

PASSING STRUCTURE TO FUNCTION IN C:

 It can be done in below 3 ways.


 Passing structure to a function by value
 Passing structure to a function by address(reference)
 No need to pass a structure – Declare structure variable as global
18
Program Example :PASSING STRUCTURE TO FUNCTION IN C BY VALUE:

19
Program Example :PASSING STRUCTURE TO FUNCTION IN C BY ADDRESS:

20
Program Example :PROGRAM TO DECLARE A STRUCTURE VARIABLE AS GLOBAL IN C:

21
Passing individual members as arguments to function.

#include<stdio.h>
struct date{
int day;
int mon;
int yr;
};
main ( ){
struct date d= {02,01,2010}; // struct date d;
display(d.day, d.mon, d.yr); // passing individual mem as argument to function
getch ( );
}
display(int a, int b, int c){
printf("day = %d\n", a);
printf("month = %d\n",b);
printf("year = %d\n",c);
}

22
Defining data type: using typedef
 One may define a structure data-type with a single
name
typedef struct newtype {
member-variable1;
member-variable2;
.
member-variableN;
} mytype;
 mytype is the name of the new data-type
 Also called an alias for struct newtype
 Writing the tag name newtype is optional, can be
skipped
 Naming follows rules of variable naming
23
Syntax of typedef
typedef <existing_name> <alias_name>  

In the above syntax, 'existing_name' is the name of an already


existing variable while 'alias name' is another name given to
the existing variable.

Forexample:
 suppose we want to create a variable of type unsigned
int, then it becomes a tedious task if we want to declare
multiple variables of this type. To overcome the problem,
we use a typedef keyword.
typedef unsigned int unit;  

24
25
Example Program:

#include<stdio.h>
#include<string.h>
typedef struct employee
{
char name[50];
int salary;
}emp;
void main( )
{
emp e1;
printf("\nEnter Employee record:\n");
printf("\nEmployee name:\t");
scanf("%s", e1.name);
printf("\nEnter Employee salary: \t");
scanf("%d", &e1.salary);
printf("\nstudent name is %s", e1.name);
printf("\nroll is %d", e1.salary);
} 26
Unit-IV

UNIONS

27
Union - Introduction
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.

28
Syntax of
Declaring Union

Defining Union

Declaring union variable,

• To access any member of a union, we use the member access operator (.).


29
Example program in Union

Another way to declare


union variable

Output.?
30
Example program to access members in union

31
Permitted Operation in Unions:

assigning a union to another union of the same type,


taking the address (&) of a union variable,
and accessing union members using the structure member operator and the structure
pointer operator.
Unions may not be compared using operators == and != for the same reasons that
structures cannot be compared.

Pointers to union

As Pointer are the variable which stores the address of other variable.
So, now will learn how store the address of Union variable.
As you know pointer can point to a variable, only if their data type are same.
For example:int type of pointer can only point to int type of variable or array,etc
Because of that ,for pointing a Union you will need to make a pointer of Union datatype. So now we will learn
how to do all that things
So , let start doing it.
for learning that we will define a Union student as name , rollno ,div as it's member.

32
Pointer to union can be created just like other pointers
to primitive data types.

Syntax
The syntax for the pointers to unions in C programming is as
follows:

union uniontag{    
datatype member 1;    
datatype member 2;    
----    
----  
 datatype member n; };

memory view of union pointer

33
34
accessing union members using pointer

C program to demonstrate example of union to pointer

35
Output..?

36
Array of union

• Like array of structures.


• Create each element of the array as individual unions.
• Allocated a memory equivalent to the maximum size of the union member.
• and any one of the union member will be accessed by array element.

37
Definition:

union student //union name


{
int rollno; //member1 ,integer variable which will store, //student roll no.
char name[20]; //member2 a character array of 20 character //which will store name of student.
char div; //member3 a character variable, //which will store division of student.
};

Syntax:Declaration of array of union
union union_name union_variable_name[size_of_array];

Declaration of array of union student


void main()
{
//declaration of student array.
union student s[10]; }

38
How to Access members of union array.

•As,you know every array element has an unique


index number,Which starts from 0 index.

•Means first array element wil have index 0,second


array element will have index 1 and So on...

Syntax | Accessing member of union array

union_variable_name[index_number].member_name;

Syntax of Accessing: Rollno of array student

Array_name[index_number].rollno;

39
40
Nested Union

• Nested Union is Union which has another Union as a


member in that Union.
• A member of Union can be Union itself , this what we call
as Nested Union.
• Let's understand it by an example.

41
42
Type-1

43
Type-2

44
Typedef and union

• The keyword Typedef is used to give


a new symbolic name for the existing
name.
• Typedef is type definitions make
code more readable by giving
application-specific names to types.
• In this example, we will create type
definition with union. 

45
46
Program to differentiate structure and Union

#include<stdio.h>
/*
union is defined above all functions so it is global.
*/

struct s
{
int var1;
double var2;
char var3;
};

union u
{
int var1; printf("\n");
double var2;
char var3; printf("Information about union variable \n\n");
};

int main() printf("Address of variable of b = %u\n", &b);


{ printf("Size of variable of b = %d\n", sizeof(b));
struct s a;
union u b; printf("Address of 1st member i.e var1 = %u\n", &b.var1);
printf("Information about structure variable \n\n"); printf("Address of 2nd member i.e var2 = %u\n", &b.var2);
printf("Address variable of a = %u\n", &a);
printf("Size of variable of a = %d\n", sizeof(a));
printf("Address of 3rd member i.e var3 = %u\n", &b.var3);
printf("Address of 1st member i.e var1 = %u\n", &a.var1); printf("\n\n");
printf("Address of 2nd member i.e var2 = %u\n", &a.var2);
printf("Address of 3rd member i.e var3 = %u\n", &a.var3); return 0;
} 47
Enumerations
The following is the way to define the enum in C:

The default value of mango is 0, apple is 1, strawberry is 2, and


papaya is 3. If we want to change these default values, then we can
do as given below:

48
Let's create a simple program of enum.

49
another example to understand the enum more clearly.

50
Some important points related to enum

 The enum names available in an enum type can have the same value.
 If we do not provide any value to the enum names, then the compiler
will automatically assign the default values to the enum names starting
from 0.
 We can also provide the values to the enum name in any order, and the
unassigned names will get the default value as the previous one plus
one.
 The values assigned to the enum names must be integral constant, i.e., it
should not be of other types such string, float, etc.
 All the enum names must be unique in their scope, i.e., if we define two
enum having same scope, then these two enums should have different
enum names otherwise compiler will throw an error.
 In enumeration, we can define an enumerated data type without the
name also.

51
Declaring Bit fields

52

You might also like