Download as pdf or txt
Download as pdf or txt
You are on page 1of 31

PROGRAMMING IN C 2023-24

UNIT III
POINTER
INTRODUCTION
A pointer is a derived data type in C. It is built from one of the fundamental datatypes available in
C. Pointers contains the memory address as their values. Memory addresses are the location in the
computer where program and data are stored.

UNDERSTANDING THE POINTERS


The computer memory is a sequential collection of storage cells as shown in the figure below.
Each cell know as a byte has a number called address associated with it.

Memory Organization

A = 10
65535

Whenever we declare a variable, the system allocates an appropriate memory location to hold the
value of the variable.
Consider the following statement int A =10 where A is a variable, 10 is the value and 65535 is
the memory address. Since the memory address are the numbers they can be assigned to variable,
such variables are called pointer variable or pointer.

Definition: A pointer is a variable that store memory address of another variable.

Pointers are built on the three concepts


1. Pointer Constant: Memory address with in computer are referred as pointer constant.
2. Pointer Values: The value is assigned to the particular variable is called pointer value.
3. Pointer Variable: A variable that contains address of another variable.

Shruthi S, Asst. Professor, GSSS SSFGC, Mysuru Page 1


PROGRAMMING IN C 2023-24

DECLARATION OF POINTER
Pointer should be declared before use them
Syntax: Data type *pointer name;
Asterisk (*) tells that variable is a pointer. Pointer name is a user defined identifier
points to variable of type datatype.
Ex: int *p;
Here p is pointer variable that points to integer datatype

Ex: float *p2; //pointer to float type


char *p3; //pointer to character type

When pointer declared, it contains garbage value i.e. it may point any value in the memory.

INITIALIZATION OF POINTER
The process of assigning the address of variable to a pointer variable is known as initialization.
Syntax: Pointer = & variable;
Where & is the address operator.
Ex: int a;
int *p;
p = &a;

Note: 1. float q;
int *p;
p = &q; //Wrong
Trying to assign address of float variable to integer pointer leads to error.

2. Pointers are flexible


Same pointer point to different data variable to different statement.
int x, y, z, *p;
p=&x;
p=&y;
p=&z;

Shruthi S, Asst. Professor, GSSS SSFGC, Mysuru Page 2


PROGRAMMING IN C 2023-24

We can also use the different pointer to point he same variable.


int z, *p, *q;
p = &z;
q = &z;

ACCESSING ADDRESS AND VALUE OF VARIABLES USING POINTERS


A variable can be accessed through pointer by using indirection operator (*).
Ex: int *p , r, q;
q = 30;
p = &q;
printf(“%d”, *p);
r =*p;
printf(“%d”,r);

The first line declares q and r as integer variable and p as pointer variable. The 2nd line assigns the
values 30 to q and 3rd line assigns address of q into p. The 4th line contains the * operator, when *
is placed before pointer then pointer return the values of variable. 5th line tells pointer value is
assigned to r variable.

Address operator (&): It gives address of the address of the variable.


Indirection operator (*): It gives the value at an address contained in the pointer.
Ex: Program to access variable through pointer.
#include<stdio.h>
void main()
{
int *p ;
int u1, u2, v;
v = 3;
u1 = 2 * (v + 5);
p = &v;
u2 = 2 * (*p + 5);
printf(“u1=%d, u2=%d”, u1,u2);
}

Shruthi S, Asst. Professor, GSSS SSFGC, Mysuru Page 3


PROGRAMMING IN C 2023-24

OUTPUT
u1= 16, u2 = 16

Program to illustrate use of * operator to access the values of variable through pointer.
#include <stdio.h>
void main( )
{
int x, y;
int *ptr;
x = 10;
ptr = &x;
y = *ptr;
printf("\nThe value of x = %d\n", x);
printf("%d is stored at address %u\n”, x, &x);
printf("%d is stored at address %u\n”, *8x, &x);
printf("%d is stored at address %u\n”, *ptr, ptr);
printf("%u is stored at address %u\n”, ptr, &ptr);
printf("%d is stored at address %u\n”, y &y);
*ptr =25;
printf("\n Now value of x = %d\n", x);
getch();
}

OUTPUT
The value of x = 10
10 is stored at address 65524
10 is stored at address 65524
10 is stored at address 65524
65524 is stored at address 65522
10 is stored at address 65520
Now value of x =25

Shruthi S, Asst. Professor, GSSS SSFGC, Mysuru Page 4


PROGRAMMING IN C 2023-24

POINTER TO POINTER
A Pointer address is stored in another pointer is called pointer to pointer.
Syntax: datatype **pointer variable;
Ex: int **p;

Ex: int *q ,**p;


p = &q;

Program to illustrate the pointer to pointer.


#include <stdio.h>
void main( )
{
int x = 22, *p, **p1;
*p = &x;
**p1 = &p;
printf(“value of x=%d”,x);
printf(“value of x=%d”,*p);
printf(“value of x=%d”,**p1);
getch();
}

OUTPUT

value of x = 22
value of x through p = 22
value of x through p1 = 22

POINTER AND ARRAY


When a array is declared, compiler allocates base address and memory location to contain all the
elements to array.
Suppose we declare an array num as follows
int num[5] = {10, 20,30, 40, 50};

Shruthi S, Asst. Professor, GSSS SSFGC, Mysuru Page 5


PROGRAMMING IN C 2023-24

Consider the base address of num is 1000 and integer requires 2 bytes, the five element will be
stores as follows.

If we declare P as an integer pointer then we can make pointer P to pint array num by using syntax.
Syntax: Pointer Variable = Array;
Ex: P = num;
Here P is pointer and num is the array.

Ex: int *P, num[5];


P = num;
or
p = &num[0];

Accessing every value of num using pointer P. P++ to move from one element to another. The
relationship between pointer and array are shown below.
P = &num[0];
P+1 = &num[1];
P+2 = & num [2];
P+3 = & num [3];
P+4 = & num [4];
we denote array elements as a num [i], where i is the index value. Similarly pointers can access
the array elements using the indirection operator (*).
*(P + i)
* is a dereferencing operator used to extract the value from the address (P + i).
P represents the pointer name and i represents the index value.
(P + i) will give the address of the array elements as the value of i changes from 0-4

Shruthi S, Asst. Professor, GSSS SSFGC, Mysuru Page 6


PROGRAMMING IN C 2023-24

Ex: #include<stdio.h>
int main()
{
int num[5] = {10, 20, 30, 40, 50};
int *P , i;
P = num;
for(i = 0; i < 5; i++)
printf("value stored in array = %d\n",*(P+i));
return 0;
}

OUTPUT
value stored in array = 10
value stored in array = 20
value stored in array = 30
value stored in array = 40
value stored in array = 50

Program to illustrate the Pointer and array.


#include <stdio.h>
int main()
{
int x[5];
int* ptr;
ptr = &x[0]; // ptr is assigned the address of array x
printf(“Enter the values of array”);
for(i = 0; i < 5; i++)
{
scanf(“%d”, &x[i]);
}
for(i = 0; i < 5; i++)

Shruthi S, Asst. Professor, GSSS SSFGC, Mysuru Page 7


PROGRAMMING IN C 2023-24

{
printf("The array element is = %d \n", *ptr);
ptr ++;
}
getch();
}

OUTPUT
Enter the values of array
12345
The array element is = 1
The array element is = 2
The array element is = 3
The array element is = 4
The array element is = 5

POINTER ARITHMETIC

The pointer can be used in arithmetic operation like addition, subtraction, multiplication, division.
Ex:
#include <stdio.h>
void main()
{
int a, b, c;
int *r, *s;
a=90, b=30;
r = &a;
s = &b
c = *r + *s;
printf(“Addition =%d\n”, c);
c = *r - *s;
printf(“Subtraction =%d\n”, c);

Shruthi S, Asst. Professor, GSSS SSFGC, Mysuru Page 8


PROGRAMMING IN C 2023-24

c = *r / *s;
printf(“Division =%d\n”, c);
c = *r * *s;
printf(“Multiplication =%d\n”, c);
getch();
}

OUTPUT
Addition = 120

Subtraction =60

Division = 3

Multiplication = 2700

ADVANTAGES AND DISADVANTAGES OF POINTER

ADVANTAGES

 Pointers are useful in proving direct access to memory.


 It is possible to return more than 1 values from the function using pointer.
 Pointer increases speed of execution because manipulation with address is faster than the
variables.
 Pointer can be used to pass the information back and forth between calling function and
called function.
 Pointer reduces storage space and complexity of variables
 Pointer allows dynamic memory allocation and deallocation
 Pointers are useful in building the data structures like stack, linked list, queue etc.

DISADVANTAGES

 If memory is allocated using pointer is not deallocate then it causes memory leakage.
 Uninitialized pointer cause error in program.
 Pointers are complicated to handle compared to variable.

Shruthi S, Asst. Professor, GSSS SSFGC, Mysuru Page 9


PROGRAMMING IN C 2023-24

USER DEFINED FUNCTIONS

A function is a sub programs with a set of statements that perform some specific task when it is
called.
Any ‘C’ program contain at least one function i.e main().
There are basically two types of function those are

1. Library function
Library functions are those functions which are already defined in C library, example printf(),
scanf(), strcat() etc. These are already declared and defined in C libraries.

2. User defined function


A User-defined functions are those functions which are defined by the user at the time of
writing program. These functions are made for code reusability and for saving time and
space.

BENEFITS OF USING FUNCTIONS


1. It provides modularity to your program's structure.
2. It makes your code reusable. Call the function by its name to use it, wherever required.
3. Debugging and editing becomes easier using functions.
4. It makes the program more readable and easy to understand.
5. By using function large and difficult program can be divided in to sub programs.
6. Function avoids repetition of code in the program.

FORMAT OF C USER DEFINED FUNCTIONS

FUNCTION DECLARATION
A general format of a function definition is to implement into two parts
1. Function header
2. Function body

Shruthi S, Asst. Professor, GSSS SSFGC, Mysuru Page 10


PROGRAMMING IN C 2023-24

Syntax : function type function Name (parameter list) Function header


{
Local variable declaration;
Executable statement;
-------------------------- Function body
--------------------------
return statement;
}

Function header: It consists of three parts, the function type, Function Name and parameter list
where Function type is the data type of the function like int, char, double, float. Function name is
an identifier and it specifies the name of the function. The parameter list declares the type and
number of arguments that the function expects when it is called. Also, the parameters in the
parameter list receives the argument values when the function is called. These parameters are
called as formal parameters.

Function body: It contains the declarations and statement for performing the required task. The
body enclosed in braces, contains three parts. Local declaration that specify the variables needed
by the function. Executable statement that performs the task of the function. A return statement
that returns the value evaluated by the function.

Ex: int addition (int a, int b)


{
int c;
c = a+b;
return c;
}

Shruthi S, Asst. Professor, GSSS SSFGC, Mysuru Page 11


PROGRAMMING IN C 2023-24

COMPONENTS OF USER DEFINED FUNCTIONS

1. Parameter list: In function there are two types of parameter.


Actual Parameter: The parameter which are used inside the function call is knows as actual
parameter and these are the original values and copy of these are actually sent to the called
function.
Ex: add (a,b);
Subtraction (20,10);
Multiply (&a, &b);

The parameter that are used inside the function call are called actual parameter.

Formal parameter: The parameter which are used in function definition are called formal
parameter. These parameter are used to hold the values that are sent by the actual parameter of
calling function through the function call.
Ex: int add (int a, int b)
void Subtraction(float a, float b)
int multiply (int *a, int *b)

The parameter that are used inside the function are called formal parameter.

The difference between actual parameter and formal parameter


Actual Parameter Formal Parameter
The parameters which are used in a function call Parameters used in the function definition
are called actual parameters. are called formal parameters.
Actual parameters can be variables, constants, Formal parameters are variables with the
and expressions, without data types. data type.
In actual parameters, there is no requirement to In formal parameters, it is mandatory to
define datatype. define the datatype.
Actual Parameters are the parameters which are Formal Parameters are the parameters
in calling function which are in called function
Ex: add (a, b); Ex: int add (int x, int y)
{ //body }

Shruthi S, Asst. Professor, GSSS SSFGC, Mysuru Page 12


PROGRAMMING IN C 2023-24

2. Function Call
A function can be called by the function name with list of actual parameters end with semicolon
is called function call. The compiler execute these functions when it is called.
Syntax: function (arg1,arg2,arg3);
Ex: addition(a,b,c);
Sub(20,30,40);
S = sum(a, b);

3. Return type
It is used to return value to the calling function. It can be used in two way as return or
return (expression); where return is the keyword having predefined meaning.
Ex: return a; // Returning the value of a to calling function
return (a*b); // Returning the value of expression a*b to calling function
return // Does not return any value.

4. Global Variables: Variables declare outside of any function. These are known throughout the
program and they will hold their value throughout the program’s execution.
Ex: int a, b; // Global variables
void main()
{
a=10, b=20;
add(a, b);
}
void add(int a, b)
{
pritnf(“%d%d”, a,b);
}

5. Local Variables: Variables that are declared inside a function are called local variables. Local
variables are not know outside their own code block. They will hold their value only inside
their function.

Shruthi S, Asst. Professor, GSSS SSFGC, Mysuru Page 13


PROGRAMMING IN C 2023-24

Ex: void add ( )


{
int a, b; // Local variables
a=10, b = 20;
}

6. Function Prototype: All the function must be declare before they are used. This can be done
by function prototype. A function definition serves as its prototype.
Syntax: function type function Name (parameter list);
Ex: int addition (int a, int b);

C PROGRAM TO ADD TWO NUMBER USING USER DEFINED FUNCTION


#include<stdio.h>
#include<conio.h>
int sum (int x, int y); Function Prototype
int a, b; Global Variables
void main()
{
int c; Local variable
printf(“enter two number”);
Calling
Function scanf(“%d%d”,&a, &b);
c = sum (a, b); Function Call, a and b are actual parameter
printf (“Addition is = %d”,c);
}
int sum(int x, int y) Function definition, x and y are formal parameter
{
int c; Local variable
Called
Function c= x+y;
return c; return statement
}

Shruthi S, Asst. Professor, GSSS SSFGC, Mysuru Page 14


PROGRAMMING IN C 2023-24

CATEGORIES OF USER DEFINED FUNCTIONS

Depending on weather parameter are present or not and weather a value is returned or not, a
function can be categorized into four as follows.

1. Function with no parameter and no return value


2. Function with no parameter but return value
3. Function with parameter but no return value
4. Function with parameter and return value

1. Function with no parameter and no return value


When function has no parameter, called function does not receive any data from the calling
function, similarly when function has no return a value, the calling function does not receive any
data from called function. There is no data transfer between calling function to called function and
vice versa.
Ex: #include<stdio.h>
#include<conio.h>
void multiply ();
void main()

Calling {
Function multiply ();
}
void multiply()
{
int x, y, c;
Called
Function x=10, y=20;
c = x*y;
printf (“Multiplication is = %d”, c);
}

OUTPUT:
Multiplication is = 200

Shruthi S, Asst. Professor, GSSS SSFGC, Mysuru Page 15


PROGRAMMING IN C 2023-24

2. Function with no parameter but return value


When function has no parameter, called function does not receive any data from the calling
function, when function has return a value, the calling function receives data from called function
using return statement. There is no data transfer between calling function to called function but
there is a data transfer between called function to calling function.
Ex: #include<stdio.h>
#include<conio.h>
int multiply ();
void main()
{
Calling int c;
Function c = multiply ();
printf (“Multiplication is = %d”, c);
}
int multiply()
{
int x, y, c;
Called
Function x=10, y=20;
c = x*y;
return c;
}

OUTPUT:
Multiplication is = 200

3. Function with parameter but no return value


When function has parameter, called function receives actual parameter value to formal parameter
from the calling function, when function has no return a value, the calling function does not receive
any data from called function. There is a data transfer between calling function to called function
but there is no data transfer between called function to calling function.

Shruthi S, Asst. Professor, GSSS SSFGC, Mysuru Page 16


PROGRAMMING IN C 2023-24

Ex: #include<stdio.h>
#include<conio.h>
void multiply (int x, int y);
void main()
{
Calling int a, b, c;
Function a = 20, b =30;
multiply (a, b);
}
void multiply(int x, int y)
{
int c;
Called
Function c = x*y;
printf (“Multiplication is = %d”, c);
}

OUTPUT:
Multiplication is = 600

4. Function with parameter and return value


When function has parameter, called function receives actual parameter value to formal parameter
from the calling function, when function has return a value, the calling function receives data from
called function through return statement. There is a data transfer between calling function to called
function and vice versa.
Ex: #include<stdio.h>
#include<conio.h>
int multiply (int x, int y);
void main()
{
Calling int a, b, c;
Function a = 20, b =30;

Shruthi S, Asst. Professor, GSSS SSFGC, Mysuru Page 17


PROGRAMMING IN C 2023-24

c = multiply (a, b);


printf (“Multiplication is = %d”, c);
}
int multiply(int x, int y)
{
int c;
Called
Function c = x*y;
return c;
}

OUTPUT:
Multiplication is = 600

PASSING PARAMTER TO FUNCTION


There are two way through which we can pass the parameter to the function such as
 Call by value or Pass by value
 Call by reference or Pass by reference

 Call by value or Pass by value


The value of actual parameter is passed to the formal parameter is called Call by value or Pass
by value.
 When the function is called by ‘call by value’ method, it doesn’t affect content of the
actual parameter.
 Any changes made to formal parameter are local to block of called function so when the
control is back to calling function will not affect the value of actual parameter.

Ex: #include<stdio.h>
#include<conio.h>
void swap(int a, int b);
void main()
{

Shruthi S, Asst. Professor, GSSS SSFGC, Mysuru Page 18


PROGRAMMING IN C 2023-24

int a, b;
clrscr();
printf("Enter value for a, b \n");
scanf("%d%d",&a,&b);
printf("Before SWAP a = %d, b = %d \n",a, b);
swap(a, b); Actual parameter value is passing
printf("After SWAP a = %d, b = %d \n",a, b);
getch();
}
void swap(int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
}

OUTPUT:
Enter value for a, b
20 30
Before SWAP a = 20, b = 30
After SWAP a = 20, b = 30

 Call by reference or Pass by reference


The address of actual parameter is passed to the formal parameter is called Call by reference
or Pass by reference.
 When the actual parameter address is passed to formal parameter, it becomes pointer.
 When the function is called by ‘call by reference’ method, it will affect content of the
actual parameter.
 Any changes made to formal parameter will affect the value of actual parameter since we
passed address.

Shruthi S, Asst. Professor, GSSS SSFGC, Mysuru Page 19


PROGRAMMING IN C 2023-24

Ex: #include<stdio.h>
#include<conio.h>
void swap(int *a, int *b);
void main()
{
int a, b;
clrscr();
printf("Enter value for a, b \n");
scanf("%d%d",&a,&b);
printf("Before SWAP a = %d, b = %d \n",a,b);
swap(&a,&b); Actual parameter address is passing
printf("After SWAP a = %d, b = %d \n",a,b);
getch();
}
void swap(int *a, int *b) Formal Pointer becomes pointer
{
int *temp;
*temp = *a;
*a = *b;
*b = *temp;
}

OUTPUT:
Enter value for a, b
20 30
Before SWAP a = 20, b = 30
After SWAP a = 30, b = 20

Shruthi S, Asst. Professor, GSSS SSFGC, Mysuru Page 20


PROGRAMMING IN C 2023-24

DIFFERNCE BETWEEN CALL BY VALUE AND CALL BY REFERNCE

Call by value Call by reference


When function is called value of variables When function is called address of variables
are passed. are passed.
The datatype of formal parameter should be The datatype of formal parameter should be
same as actual parameter. same as actual parameter but it is declared as
pointer.
Formal parameter holds value of actual Formal parameter holds address of actual
parameter. parameter.
Change of formal parameter in called Change of formal parameter in called
function will not affect the actual parameter function will affect the actual parameter in
in calling function. calling function.
Execution is slower since all values should Execution is faster since only address is
pass. pass.

Shruthi S, Asst. Professor, GSSS SSFGC, Mysuru Page 21


PROGRAMMING IN C 2023-24

USER DEFINED DATA TYPES


STRUCTURES
A structure is one of a user defined data type. A Structure creates a data type that can be used to
group items of possibly different types into a single type.

STRUCTURE DEFINITION
It is the logically related collection of dissimilar data types grouped together to form a single entity.

STRUCTURE DECLARATION
Syntax: struct structure name
{
data type member1;
data type member2;
………
………
data type member n;
};
Where struct is a keyword, Structure name defines the name of the structure defined by user. N
numbers of dissimilar data members can be defined inside the structure.

Ex: struct student Structure name


{
char name[20];
int Reg; Structure members
float marks;
};
name is variable of type char, Reg is variable of type int and marls is variable of type float.
Memory Representation of Structure is as follows.
Compiler will allocate the memory for individual members of structure.

20 bytes 2 bytes 4 bytes

name Reg marks


Shruthi S, Asst. Professor, GSSS SSFGC, Mysuru Page 22
PROGRAMMING IN C 2023-24

DECLARING STRUCTURE VARIABLES


A structure variable can be defined by using following syntax.
Syntax: struct structure name structure variable1, structure variable1, structure variable1;
Ex: struct student s1, s2, s3;
It is possible to create one or more structure variable which is separated by comma (,)

Ex: struct student


{
char name[20];
int Reg;
float marks;
};
struct student s1, s2, s3;
Where s1, s2, s3 are variables of type struct student
Ex: struct student
{
char name[20];
int Reg;
float marks;
}; s1, s2, s3;
It is also valid. The use of structure name is optional.

ACCESSING STRUCTURE MEMBERS


Structure member can be accessed by using member operator or dot operator (.)
Synatx: structure variable . Structure member;
Ex: s1. name;
Members of structure are stored in contiguous memory locations.

We can assign values to structure member and use scanf() function to give values.
Ex: scanf (“%s”, s1.name);
scanf (“%d”, &s1.Reg);

Shruthi S, Asst. Professor, GSSS SSFGC, Mysuru Page 23


PROGRAMMING IN C 2023-24

C Program to illustrate the structure:


#include<stdio.h>
#include<conio.h>
struct student
{
char name[20];
int Reg;
float marks;
};
void main()
{
Struct student s1;
printf(“\n enter name, Reg, marks\n”);
scanf(“%s %d %f”, s1. name, &s1. Reg, &s1. marks);
printf(“ students details are \n”);
printf(“Name= %s”, s1. name);

printf(“Reg. number=%d”, s1. Reg);

printf(“Marks =%f”, s1. marks);


}

OUTPUT:
enter name, Reg, marks
Shruthi
16
67.4
students details are
Name = Shruthi
Reg. number = 16
Marks = 67.4

Shruthi S, Asst. Professor, GSSS SSFGC, Mysuru Page 24


PROGRAMMING IN C 2023-24

STRUCTURE MEMBERS INITIALIZATION


A structure can be initialized as
struct student
{
char name[20];
int Reg;
float marks;
} s1 = {sona”, 12, 45.6};
s2 = {“rupa”, 14, 76.5};
s3 = {“uma”, 17, 86.5};

This assigns the value sona to s1.name , 12 to s1.Reg and 45.6 to s1.marks and so on.
Another method to initialize a structure variable inside the main function
struct student
{
char name[20];
int Reg;
float marks;
};
void main( )
{
struct student s1 = {sona”, 12, 45.6};
struct student s2 = {“rupa”, 14, 76.5};
------------------------------------
}

 The order of values enclosed in the braces must match the order of member in the structure
definition.
 It is permitted have a partial initialization but it should be at the end. The uninitialized members
will be assigned default value as zero for int, float, double and \0 for char and string.

Shruthi S, Asst. Professor, GSSS SSFGC, Mysuru Page 25


PROGRAMMING IN C 2023-24

ARRAY OF STRUCTURES
Suppose we want to maintain data base of 200 students, Array of structures is used. To declare
array of structure a structure variable is declare with array.

Ex: strcut student s1 [200];

Consider the following declaration


struct student
{
char name[20];
int Id;
};
struct student s1[3] ={ {“Shruthi”, 12}, {“Anu”, 1}, {“Banu”, 2}};
this declares the student as an array of three elements s1[0], s1[1] and s1[2] and initializes their
member as follows.
s1[0] . name = Shruthi

s1[0] . Id = 12

s1[1] . name = Anu

s1[1] . Id = 1

s1[2] . name = Banu

s1[2] . Id = 2

C Program to illustrate the array of structure


#include<stdio.h>
#include<conio.h>
struct student
{
char name[20];
int Id;
};

Shruthi S, Asst. Professor, GSSS SSFGC, Mysuru Page 26


PROGRAMMING IN C 2023-24

void main()
{
struct student s1[3] ={ {“Shruthi”, 12}, {“Anu”, 1}, {“Banu”, 2}};
int i;
printf(“The details of Students\n”);
for(i = 0; i < 3; i++)
{
printf(“Name = %s”, s[i] . name);
printf(“Id = %d”, s[i] . Id);
getch();
}

OUTPUT:
The details of Students
Name = Shruthi
Id = 12
Name = Anu
Id = 1
Name = Banu
Id = 2

Note: Another example program for array of structure Refer Lab program Part B – Program 10.

SIZE OF STRUCTURE
Size of structure can be find using sizeof() operator with structure variable name or structure name
with keyword.

Syntax: sizeof(structure variable); or sizeof(struct structure name);


Ex: sizeof(s1); or sizeof(struct student);

Shruthi S, Asst. Professor, GSSS SSFGC, Mysuru Page 27


PROGRAMMING IN C 2023-24

ADVANTAGES OF STRUCTURE
1. Structure allows us to create user defined data-type which can store items with different
data types.
2. Structure Reduced complexity of program
3. It is very easy to maintain complex records by using single name.
4. Array of structure are used to store more records with similar types

DISADVANTAGES
1. Structure occupies memory space for each and every member.
2. Structure is slower because it requires storage space for all the data.

UNION
Union is derived data type contains collection of different data type or dissimilar elements. All
definition declaration of union variable and accessing member is similar to structure, but instead
of keyword struct the keyword union is used, the main difference between union and structure is
Each member of structure occupy the memory location, but in the unions members share memory.
Union is used for saving memory.

Syntax : union union name


{
datatype member1;
datatype member2;
………
………
data type member n;
};
Like structure variable, union variable can be declared with definition or separately such as
Syntax: union union name union variable.

Shruthi S, Asst. Professor, GSSS SSFGC, Mysuru Page 28


PROGRAMMING IN C 2023-24

Ex: union student


{
int i;
char ch[10];
};
union student s;
Union members can also be accessed by the dot operator (.) with union variable.

Memory Representation of Structure is as follows.


Compiler will allocate the memory of highest size members of union. It shared by all the members
of the union
10 bytes

Shared by all members

C Program to illustrate the union


#include <stdio.h>
#include<conio.h>
union marks
{
int sub1;
float sub2;
};
void main( )
{
union marks m;
printf(“\n enter marks\n”);
scanf(“ %d %f”, &m. sub1, &m. sub2);
printf(“The details of marks\n”);
printf("Sub1=%d\n", m. sub1);

printf("Sub2=%f\n", m. sub2);
}

Shruthi S, Asst. Professor, GSSS SSFGC, Mysuru Page 29


PROGRAMMING IN C 2023-24

OUTPUT
enter marks
45 75.5
The details of marks
Sub1 = 45
Sub2 = 75.5

Note:
Ex:- struct student
{
int i;
char ch[10];
};
struct student s;

Here datatype/member of structure occupy 12 byte of location is memory,

union student
{
int i;
char ch[10];
};
union student s;

Whereas the union occupies only 10 byte. The highest datatype size will be allocate for union.

Advantages:
1. It occupies less memory compared to structure
2. Union enables to hold data of only one data member.

Shruthi S, Asst. Professor, GSSS SSFGC, Mysuru Page 30


PROGRAMMING IN C 2023-24

Disadvantages:
1. Union can access only one member at a time.
2. All the union member cannot be initialized at once.

DIFFERENCE BETWEEN STRUCTURE AND UNION

STRUCTURE UNION

The keyword struct is defined as a structure The keyword union is used to define a union.

The size of the structure is greater than or The size of union is equal to the size of largest
equal to the sum of size of its member. member.
Complier allocates unique memory for all the Memory allocated is shared by individual
structure members. members of the union.
Altering the value of a member will not affect Altering the value of any of the members will
other members of the structure. alter other member’s values.

Individual member can be accessed at a time Only one member can be accessed at a time.

All members of a structure can be initialized at Only the first member of the union can be
once. initialized
Ex: struct book Ex: union book
{ {
int book_id; int book_id;
char book_name[10]; char book_name[10];
}; };
struct book b; union book b;

Shruthi S, Asst. Professor, GSSS SSFGC, Mysuru Page 31

You might also like