0% found this document useful (0 votes)
27 views35 pages

Unit-2 C - MCA

The document discusses different types of functions in C programming language. It explains function declaration, definition, call and advantages of using functions. It also describes system defined functions, user defined functions and different types of user defined functions based on parameters and return values. Finally, it discusses parameter passing methods - call by value and call by reference.

Uploaded by

bhavanapulidindi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
27 views35 pages

Unit-2 C - MCA

The document discusses different types of functions in C programming language. It explains function declaration, definition, call and advantages of using functions. It also describes system defined functions, user defined functions and different types of user defined functions based on parameters and return values. Finally, it discusses parameter passing methods - call by value and call by reference.

Uploaded by

bhavanapulidindi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 35

UNIT-2

FUNCTIONS, POINTERS, STRUCTURES AND UNIONS, FILES


I) Introduction to Functions:
When we write a program to solve a larger problem, we divide that larger problem into
smaller subproblems and are solved individually to make the program easier. In C, this concept is
implemented using functions. Functions are used to divide a larger program into smaller
subprograms such that the program becomes easy to understand and easy to implement. A function
is defined as follows...

Function is a subpart of a program used to perform a specific task and is executed


individually.

Every C program must contain at least one function called main(). However, a program
may also contain other functions.

Every function in C has the following...


• Function Declaration (Function Prototype)
• Function Definition
• Function Call

1) Function Declaration: The function declaration tells the compiler about function name, the data
type of the return value and parameters. The function declaration is also called a function
prototype. The function declaration is performed before the main function or inside the main
function or any other function.

Function declaration syntax -

• returnType functionName(parametersList);

In the above syntax, returnType specifies the data type of the value which is sent as a return
value from the function definition. The functionName is a user-defined name used to identify the
function uniquely in the program. The parametersList is the data values that are sent to the
function definition.

2) Function Definition: The function definition provides the actual code of that function. The
function definition is also known as the body of the function. The actual task of the function is
implemented in the function definition. That means the actual instructions to be performed by a
function are written in function definition. The actual instructions of a function are written inside
the braces "{ }". The function definition is performed before the main function or after the main
function.

Function definition syntax -

returnType functionName(parametersList)
{

Actual code...

3) Function Call : The function call tells the compiler when to execute the function definition.
When a function call is executed, the execution control jumps to the function definition where the
actual code gets executed and returns to the same functions call once the execution completes. The
function call is performed inside the main function or any other function or inside the function
itself.

Function call syntax -

functionName(parameters);

Advantages:
• Using functions we can implement modular programming.
• Functions make the program more readable and understandable.
• Using functions the program implementation becomes easy.
• Once a function is created it can be used many times (code re-usability).
• Using functions larger programs can be divided into smaller modules.
In C Programming Language, based on providing the function definition, functions are divided
into two types. Those are as follows...

• System Defined Functions


• User Defined Functions

a) System Defined Functions: These pre-defined functions are known as system defined
functions. The system defined function is defined as follows...
The function whose definition is defined by the system is called as system defined function.

The system defined functions are also called as Library Functions or Standard
Functions or Pre-Defined Functions. The implementation of system defined functions is already
defined by the system. Example : printf(), scanf(), sqrt(), abs(), pow() etc.

b) User Defined Functions: In C programming language, users can also create their own
functions. The functions that are created by users are called as user defined functions. The user
defined function is defined as follows...

The function whose definition is defined by the user is called as user defined function.

II) Purpose Return statement: The return statement is used to terminate the execution of a
function and transfer program control back to the calling function. In addition, it can specify a
value to be returned by the function. A function may contain one or more return statements. The
general format of the return statement is given below.
return expr or value ;
Example:
void main()
{
int sum = sumDigits();
printf("%d\n", sum);
return;
}
int sumDigits()
{
int sum = 0; int digit;
for(digit = 0; digit <= 9; ++digit)
{
sum += digit;
}
return sum;
}
III) Types of user Defined functions:
• Function without Parameters and without Return value
• Function with Parameters and without Return value
• Function without Parameters and with Return value
• Function with Parameters and with Return value
1) Function without Parameters and without Return value: In this type of functions there is no data
transfer between calling function and called function. Simply the execution control jumps from calling-
function to called function and executes called function, and finally comes back to the calling function. For
example, consider the following program...

#include<stdio.h>
#include<conio.h>
void main(){
void addition() ; // function declaration
clrscr() ;
addition() ; // function call
getch() ;
}
void addition() // function definition
{
int num1, num2 ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
printf("Sum = %d", num1+num2 ) ;
}

2) Function with Parameters and without Return value : In this type of functions there is data
transfer from calling-function to called function (parameters) but there is no data transfer from
called function to calling-function (return value). The execution control jumps from calling-
function to called function along with the parameters and executes called function, and finally
comes back to the calling function. For example, consider the following program...

#include<stdio.h>
#include<conio.h>
void main(){
int num1, num2 ;
void addition(int, int) ; // function declaration
clrscr() ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
addition(num1, num2) ; // function call
getch() ;
}
void addition(int a, int b) // function definition
{
printf("Sum = %d", a+b ) ;
}
3) Function without Parameters and with Return value: In this type of functions there is no
data transfer from calling-function to called-function (parameters) but there is data transfer from
called function to calling-function (return value). The execution control jumps from calling-
function to called function and executes called function, and finally comes back to the calling
function along with a return value. For example, consider the following program...
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
int result ;
int addition() ; // function declaration
clrscr() ;
result = addition() ; // function call
printf("Sum = %d", result) ;
getch() ;
}
int addition() // function definition
{
int num1, num2 ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
return (num1+num2) ;
}
4) Function with Parameters and with Return value
In this type of functions there is data transfer from calling-function to called-function (parameters)
and also from called function to calling-function (return value). The execution control jumps from
calling-function to called function along with parameters and executes called function, and finally
comes back to the calling function along with a return value. For example, consider the following
program...
Example Program
#include<stdio.h>

#include<conio.h>

void main(){

int num1, num2, result ;

int addition(int, int) ; // function declaration

clrscr() ;

printf("Enter any two integer numbers : ") ;

scanf("%d%d", &num1, &num2);

result = addition(num1, num2) ; // function call

printf("Sum = %d", result) ;

getch() ;

int addition(int a, int b) // function definition


{
return (a+b) ;
}

Points to be Remembered

• The parameters specified in calling function are said to be Actual Parameters.

• The parameters declared in called function are said to be Formal Parameters.

• The value of actual parameters is always copied into formal parameters.

IV) Parameter passing methods:


In C Programming Language, there are two methods to pass parameters from calling
function to called function and they are as follows...

• Call by Value
• Call by Reference

1) Call by Value : In call by value parameter passing method, the copy of actual parameter values
are copied to formal parameters and these formal parameters are used in called function. The
changes made on the formal parameters do not effect the values of actual parameters. That
means, after the execution control comes back to the calling function, the actual parameter values
remains same. For example consider the following program...

Example Program :

#include<stdio.h>
#include<conio.h>
void main(){
int num1, num2 ;
void swap(int,int) ; // function declaration
clrscr() ;
num1 = 10 ;
num2 = 20 ;
printf("\nBefore swap: num1 = %d, num2 = %d", num1, num2) ;
swap(num1, num2) ; // calling function
printf("\nAfter swap: num1 = %d\nnum2 = %d", num1, num2);
getch() ;
}
void swap(int a, int b) // called function
{
int temp ;
temp = a ;
a=b;
b = temp ;
}

2) Call by Reference: In Call by Reference parameter passing method, the memory location
address of the actual parameters is copied to formal parameters. This address is used to access the
memory locations of the actual parameters in called function. In this method of parameter passing,
the formal parameters must be pointer variables.
That means in call by reference parameter passing method, the address of the actual
parameters is passed to the called function and is recieved by the formal parameters (pointers).
Whenever we use these formal parameters in called function, they directly access the memory
locations of actual parameters. So the changes made on the formal parameters effects the values of
actual parameters. For example consider the following program...

Example :

#include<stdio.h>
#include<conio.h>
void main(){
int num1, num2 ;
void swap(int *,int *) ; // function declaration
clrscr() ;
num1 = 10 ;
num2 = 20 ;
printf("\nBefore swap: num1 = %d, num2 = %d", num1, num2) ;
swap(&num1, &num2) ; // calling function
printf("\nAfter swap: num1 = %d, num2 = %d", num1, num2);
getch() ;
}
void swap(int *a, int *b) // called function
{
int temp ;
temp = *a ;
*a = *b ;
*b = temp ;
}

V) Storage Classes:
In C programming language, storage classes are used to define things like storage
location (whether RAM) scope, lifetime and the default value of a variable.
In C programming language, there are FOUR storage classes and they are as follows...
• auto storage class
• extern storage class
• static storage class
• register storage class

1) Auto storage class: The default storage class of all local variables (variables declared inside
block or function) is auto storage class. Variable of auto storage class has the following
properties...

Property Description

Keyword auto

Storage Computer Memory (RAM)

Default Value Garbage Value

Scope Local to the block in which the variable is defined

Life time Till the control remains within the block in which variable is
defined

Example :

#include<stdio.h>
#include<conio.h>
int main(){
auto int a=10;
{
auto int a=20;
printf("%d",a);
}
printf(" %d",a);
return 0;
}
2) External storage class : The default storage class of all global varibles (variables declared
outside function) is external storage class. Variable of external storage class has the following
properties...

Property Description

Keyword extern

Storage Computer Memory (RAM)

Default Value Zero

Scope Global to the program (i.e., Throughout the program)

Life time As long as the program’s execution does not comes to end

Example:
#include<stdio.h>
#include<conio.h>
int i; //By default it is extern variable
int main(){
printf("%d",i);
return 0;
}

3) Static storage class : The static storage class is used to create variables that hold value beyond
its scope until the end of the program. The static variable allows to initialize only once and can be
modified any number of times. Variable of static storage class has the following properties...

Property Description

Keyword static

Storage Computer Memory (RAM)


Property Description

Default Value Zero

Scope Local to the block in which the variable is defined

Life time The value of the persists between different function calls (i.e.,
Initialization is done only once)

Example:

void sum()
{
static int a = 10;
static int b = 24;
printf("%d %d \n",a,b);
a++;
b++;
}
void main()
{
int i;
for(i = 0; i< 3; i++)
{
sum(); // The static variables holds their value between multiple function calls.
}
}

4) Register storage class : The register storage class is used to specify the memory of the variable
that has to be allocated in CPU Registers. The memory of the register variable is allocated in CPU
Register but not in Computer memory (RAM). The register variables enable faster accessibility
compared to other storage class variables. As the number of registers inside the CPU is very less
we can use very less number of register variables. Variable of register storage class has the
following properties...

Property Description

Keyword register

Storage CPU Register

Default Value Garbage Value

Scope Local to the block in which the variable is defined

Life time Till the control remains within the block in which variable is
defined.

Example:

#include<stdio.h>

#include<conio.h>

int main(){

register int a,b;

scanf("%d%d",&a,&b);

printf("%d %d",a,b);

VI) Recursion:
In C programming language, function calls can be made from the main() function, other
functions or from the same function itself. The recursive function is defined as follows...
A function called by itself is called recursive function.
There are 2 type of recursion:
• Direct Recursion
• Indirect Recursion
1) Direct Recursion: When a function calls itself within the same function repeatedly, it is
called the direct recursion.

Example:

#include<stdio.h>
#include<conio.h>
int factorial( int ) ;
int main()
{
int fact, n ;
printf("Enter any positive integer: ") ;
scanf("%d", &n) ;
fact = factorial( n ) ;
printf("\nFactorial of %d is %d\n", n, fact) ;
return 0;
}
int factorial( int n )
{
int temp ;
if( n == 0)
return 1 ;
else
temp = n * factorial( n-1 ) ; // recursive function call
return temp ;
}

Explanation:
2) Indirect recursion: When a function is mutually called by another function in a circular manner, the
function is called an indirect recursion function.
Example :
int fact1(int);
int fact2(int);
void main()
{
printf("%d", fact1(5));
getch();
}
int fact1(int n)
{
if(n==1)
return 1;
else
return n*fact2(n-1);
}
int fact2(int n)
{
if(n==1)
return 1;
else
return n*fact1(n-1);
}
Pointers
I) Introduction Pointers:
In the c programming language, we use normal variables to store user data values. When we
declare a variable, the compiler allocates required memory with the specified name. In the c
programming language, every variable has a name, datatype, value, storage class, and address. We
use a special type of variable called a pointer to store the address of another variable with the same
datatype. A pointer is defined as follows...

Pointer is a special type of variable used to store the memory location address of a variable.

In the c programming language, we can create pointer variables of any datatype. Every
pointer stores the address the variable with same datatype only. That means integer pointer is used
store the address of integer variable only.

Accessing the Address of Variables: In c programming language, we use the reference operator
"&" to access the address of variable. For example, to access the address of a
variable "marks" we use "&marks". We use the following printf statement to display memory
location address of variable "marks"...

Example Code

printf("Address : %u", &marks) ;

Declaring Pointers (Creating Pointers) : In c programming language, declaration of pointer


variable is similar to the creation of normal variable but the name is prefixed with * symbol. We
use the following syntax to declare a pointer variable...

datatype *pointerName ;

A variable declaration prefixed with * symbol becomes a pointer variable.

Example Code

int *ptr ;

Assigning Address to Pointer : To assign address to a pointer variable we use assignment


operator with the following syntax...

pointerVariableName = & variableName ;


Example: int a, *ptr ;
ptr = &a ;
Example Program:
#include<stdio.h>
#include<conio.h>
void main()

int a = 10, *ptr ;

clrscr();

ptr = &a ;

printf("Address of variable a = %u\n", ptr) ;

printf("Value of variable a = %d\n", *ptr) ;

printf("Address of variable ptr = %u\n", &ptr) ;

Addition Operator in Pointers:

Addition Operation on Pointer


In the c programming language, the addition operation on pointer variables is calculated using the
following formula...

AddressAtPointer + ( NumberToBeAdd *
BytesOfMemoryRequiredByDatatype )
Example Program
void main()
{
int a, *intPtr ;
float b, *floatPtr ;
double c, *doublePtr ;
clrscr() ;
intPtr = &a ; // Asume address of a is 1000
floatPtr = &b ; // Asume address of b is 2000
doublePtr = &c ; // Asume address of c is 3000

intPtr = intPtr + 3 ; // intPtr = 1000 + ( 3 * 2 )


floatPtr = floatPtr + 2 ; // floatPtr = 2000 + ( 2 * 4 )
doublePtr = doublePtr + 5 ; // doublePtr = 3000 + ( 5 * 6 )
printf("intPtr value : %u\n", intPtr) ;
printf("floatPtr value : %u\n", floatPtr) ;
printf("doublePtr value : %u", doublePtr) ;
getch() ;
}
II) Pointers to Pointers in C :
In the c programming language, we have pointers to store the address of variables of any
datatype. A pointer variable can store the address of a normal variable. C programming language
also provides a pointer variable to store the address of another pointer variable. This type of pointer
variable is called a pointer to pointer variable. Sometimes we also call it a double pointer. We use
the following syntax for creating pointer to pointer…
datatype **pointerName ;

Example : int **ptr ;


Example Program:
#include<stdio.h>
#include<conio.h>
int main()
{
int a ;
int *ptr1 ;
int **ptr2 ;
int ***ptr3 ;
ptr1 = &a ;
ptr2 = &ptr1 ;
ptr3 = &ptr2 ;
printf("\nAddress of normal variable 'a' = %u\n", ptr1) ;
printf("Address of pointer variable '*ptr1' = %u\n", ptr2) ;
printf("Address of pointer-to-pointer '**ptr2' = %u\n", ptr3) ;
return 0;
}
III) Types of Pointers in C:
1) Void Pointers
2) NULL Pointers
3) Dangling Pointers
4) Function Pointers

1) Void Pointers : Till now, we have studied that the address assigned to a pointer should be of
the same type as specified in the pointer declaration. For example, if we declare the int pointer,
then this int pointer cannot point to the float variable or some other type of variable, i.e., it can
point to only int type variable. To overcome this problem, we use a pointer to void. A pointer to
void means a generic pointer that can point to any data type. We can assign the address of any
data type to the void pointer, and a void pointer can be assigned to any type of the pointer
without performing any explicit typecasting.

Example :

#include<stdio.h>
int main()
{
int a=56; // initialization of a integer variable 'a'. float
b=4.5; // initialization of a float variable 'b'. char c='k'; //
initialization of a char variable 'c'. void *ptr; //
declaration of void pointer.
// assigning the address of variable 'a'.
ptr=&a;
printf("value of 'a' is : %d",*((int*)ptr));
// assigning the address of variable 'b'.
ptr=&b;
printf("\nvalue of 'b' is : %f",*((float*)ptr));
// assigning the address of variable 'c'.
ptr=&c;
printf("\nvalue of 'c' is : %c",*((char*)ptr)); return
0;
}

Output:

2) NULL pointer : A Null Pointer is a pointer that does not point to any memory location. It
stores the base address of the segment. The null pointer basically stores the Null value while void
is the type of the pointer.
A null pointer is a special reserved value which is defined in a stddef header file. Here, Null
means that the pointer is referring to the 0th memory location.
If we do not have any address which is to be assigned to the pointer, then it is known as a null
pointer. When a NULL value is assigned to the pointer, then it is considered as a Null pointer.

Example :

#include <stdio.h> int


main() {
int *p= NULL;//initialize the pointer as null.
printf("The value of pointer is %u",p); return 0;
}
Output : The value of pointer is 0.
3) Dangling pointer : A dangling pointer is a pointer that points to a memory location
where an object no longer exists. A dangling pointer comes into existence when we delete
or de-allocate an object/variable without modifying the value of the incoming pointer so
that the pointer still points to the memory location of the deallocated memory.

Example :

#include<stdio.
h> int *call();
int
main(){
int *ptr;
ptr=call()
;
fflush(std
in);
printf("%d",*p
tr); return 0;
}
int * call(){
static int
x=25;
++x;
return &x;
}
3) Function Pointers :
Function Pointers point to code like normal pointers.
In Functions Pointers, function’s name can be used to get function’s address.
A function can also be passed as an arguments and can be returned from a function.

Declaration : function_return_type(*Pointer_name)(function argument list)

Example :

#include<stdio.h>
int subtraction (int a, int b)
{

return a-b;
}
int main() {
int (*fp) (int, int)=subtraction;
//Calling function using function pointer
int result = fp(5, 4);
printf(" Using function pointer we get the result: %d",result);
return 0;
}

Output: Using function pointer we get the result: 1

IV) Dynamic memory allocation Functions:


As you know, an array is a collection of a fixed number of values. Once the size of
an array is declared, you cannot change it.

Sometimes the size of the array you declared may be insufficient. To solve this issue,
you can allocate memory manually during run-time. This is known as dynamic memory
allocation in C programming. To allocate memory dynamically, library functions are
malloc(), calloc(), realloc() and free() are used. These functions are defined in the
<stdlib.h> header file.
1) C malloc() : The name "malloc" stands for memory allocation. The malloc()
function reserves a block of memory of the specified number of bytes. And, it returns
a pointer of void which can be casted into pointers of any form.

Syntax : (castType*) malloc(size);

Example : ptr = (float*) malloc(100 * sizeof(float));


The above statement allocates 400 bytes of memory. It's because the size of float is
4 bytes. And, the pointer ptr holds the address of the first byte in the allocated memory. The
expression results in a NULLpointer if the memory cannot be allocated.

2) calloc() : The calloc() in C is a function used to allocate multiple blocks of memory


having the same size .
Syntax : ptr = (castType*)calloc(n, size);

Example: ptr = (float*) calloc(25, sizeof(float));


3) realloc() : If the dynamically allocated memory is insufficient or more than required,
you can change the size of previously allocated memory using the realloc() function.

Syntax : ptr = realloc (ptr,newsize);

Example : ptr = realloc(ptr, n2 * sizeof(int));

4) free(): Dynamically allocated memory created with either calloc() or malloc() doesn't
get freed on their own. You must explicitly use free() to release the space.

Syntax: free(pointer Variable);

Example: free(ptr);

Program on malloc() :

// Program to calculate the sum of n numbers entered by the user


#include <stdio.h>

#include<stdli.h>

int main()

{
int n, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
ptr = (int*) malloc(n * sizeof(int));
// if memory cannot be
allocated if(ptr == NULL)
{
printf("Error! memory not
allocated."); exit(0);
}
printf("Enter elements: ");

for(i = 0; i < n; ++i)

scanf("%d", ptr + i);


sum += *(ptr + i);
}
printf("Sum = %d", sum);
// deallocating the
memory free(ptr);
return 0;
}
Progarm on realloc():
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
ptr = (int*) calloc(n, sizeof(int));
if(ptr == NULL)
{
printf("Error! memory not allocated."); exit(0);
}
printf("Enter elements: ");

for(i = 0; i < n; ++i)


{
scanf("%d", ptr );
sum += *(ptr + i);
}
printf("Sum = %d", sum);
free(ptr);
return 0;
}

Program on realloc();

#include<stdio.h>
#include <stdlib.h>

int main()
{
int *ptr, i , n1, n2;
printf("Enter size: ");
scanf("%d", &n1);
ptr = (int*) malloc(n1 * sizeof(int));
printf("Addresses of previously allocated memory: ");
for(i = 0; i < n1; ++i)
printf("%u\n",ptr + i);
printf("\nEnter the new size: ");
scanf("%d", &n2);
// rellocating the memory
ptr = realloc(ptr, n2 * sizeof(int));

printf("Addresses of newly allocated memory: ");

for(i = 0; i < n2; ++i)


printf("%u\n", ptr i);
free(ptr);
return 0;
}

V) Pointer to Array:

Use a pointer to an array, and then use that pointer to access the array elements. For example,

#include<stdio.h>
void main()
{
int a[3] = {1, 2, 3};
int *p = a;

for (int i = 0; i < 3; i++)


{
printf("%d", *p);
p++;
}
return 0;
}

Array of Pointers

Like an array of variables, we can also use array of pointers in c.


Let's create an array of 5 pointers.
int *arr[5];
Where arr[0] will hold one integer variable address, arr[1] will hold another integer variable.

EXAMPLE :

#include<stdio.
h> int main()
{
int *arr[5];
int a = 10, b = 20, c = 30, d = 40, e = 50, i;
arr[0] = &a;
arr[1] = &b;
arr[2] = &c;
arr[3] = &d;
arr[4] = &e;
printf("Address of a = %p\n",arr[0]);
printf("Address of b = %p\n",arr[1]);
printf("Address of c = %p\n",arr[2]);
printf("Address of d = %p\n",arr[3]);
printf("Address of e = %p\n",arr[4]);
for(i = 0; i < size; i++)
printf("value stored at arr[%d] = %d\n",i,*arr[i]);
return 0;
}
Structures and Unions

I) Introduction to Structures:
In C programming language, a structure is a collection of elements of the different data
type. The structure is used to create user-defined data type in the C programming language.
As the structure used to create a user-defined data type, the structure is also said to be “user-
defined data type in C”.

In other words, a structure is a collection of non-homogeneous elements. Using


structure we can define new data types called user-defined data types that holds multiple
values of the different data type. The formal definition of structure is as follows...

Structure is a collection of different type of elements under a single name that acts as
user defined data type in C.

Generally, structures are used to define a record in the c programming language. Structures
allow us to combine elements of a different data type into a group. The elements that are
defined in a structure are called members of structure.

How to create structure?


To create structure in c, we use the keyword called "struct". We use the following syntax to
create structures in c programming language.

struct <structure_name>
{
data_type member1;
data_type member2, member3;
.
.
};

Following is the example of creating a structure called Student which is used to hold student
record.

Creating structure in C :
struct Student
{
char stud_name[30];
int roll_number;
float percentage;
};
Creating and Using structure variables:

In a c programming language, there are two ways to create structure variables. We can create
structure variable while defining the structure and we can also create after terminating
structure using struct keyword.

To access members of a structure using structure variable, we use dot (.) operator.
Consider the following example code...

Creating and Using structure variables in C

struct Student

char stud_name[30];

int roll_number;

float percentage;

} stud_1 ; // while defining structure

void main(){

struct Student stud_2; // using struct keyword

printf("Enter details of stud_1 : \n");

printf("Name : ");

scanf("%s", stud_1.stud_name);

printf("Roll Number : ");

scanf("%d", &stud_1.roll_number);

printf("Percentage : ");

scanf("%f", &stud_1.percentage);

printf("***** Student 1 Details *****\n);

printf("Name of the Student : %s\n", stud_1.stud_name);


printf("Roll Number of the Student : %i\n", stud_1.roll_number);

printf("Percentage of the Student : %f\n", stud_1.percentage);

Memory allocation of Structure: When the structures are used in the c programming
language, the memory does not allocate on defining a structure. The memory is allocated
when we create the variable of a particular structure. As long as the variable of a structure is
created no memory is allocated. The size of memory allocated is equal to the sum of memory
required by individual members of that structure. In the above example program, the
variables stud_1 and stud_2 are allocated with 36 bytes of memory each.

II) Array of Structures in C:


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.
Example:

#include<stdio.h>

#include <string.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);

return 0;

}
III) Structure Pointer:
The structure pointer points to the address of a memory block where the Structure is
being stored. Like a pointer that tells the address of another variable of any data type (int,
char, float) in memory. And here, we use a structure pointer which tells the address of a
structure in memory by pointing pointer variable ptr to the structure variable.
Declare a Structure Pointer
The declaration of a structure pointer is similar to the declaration of the structure
variable. So, we can declare the structure pointer and variable inside and outside of the
main() function. To declare a pointer variable in C, we use the asterisk (*) symbol before the
variable's name.
struct structure_name *ptr;

Initialization of the Structure Pointer


ptr = &structure_variable;

Access Structure member using pointer: There are two ways to access the member of the
structure using Structure pointer:
1. Using ( * ) asterisk or indirection operator and dot ( . ) operator.
2. Using arrow ( -> ) operator or membership operator.

Example : #include <stdio.h>


struct my_structure {
char name[20];
int number;
int rank;
};
int main()
{
struct my_structure variable = {"StudyTonight", 35, 1};
struct my_structure *ptr;
ptr = &variable;
printf("NAME: %s\n", ptr->name);
printf("NUMBER: %d\n", ptr->number);
printf("RANK: %d", ptr->rank);
return 0; }
IV) Introduction to Unions:
In C programming language, the union is a collection of elements of the different data
type. The union is used to create user-defined data type in the C programming language. As
the union used to create a user-defined data type, the union is also said to be “user-defined
data type in C”.
In other words, the union is a collection of non-homogeneous elements. Using union we can
define new data types called user-defined data types that holds multiple values of the
different data type. The formal definition of a union is as follows...

Union is a collection of different type of elements under a single name that acts as user
defined data type in C.

How to create union?

To create union in c, we use the keyword called "union". We use the following syntax to create
unions in c programming language.

union <structure_name>
{
data_type member1;
data_type member2, member3;
.
.
};

Following is the example of creating a union called Student which is used to hold student record.
Creating union in C

union Student

char stud_name[30];

int roll_number;

float percentage;

};
Creating and using union variables : In a c programming language, there are two ways to
create union variables. We can create union variable while the union is defined and we can
also create after terminating union using union keyword.

TO access members of a union using union variable, we use dot (.) operator. Consider
the following example code...

Creating and Using union variables in C


union Student
{
char stud_name[30];
int roll_number;
float percentage;
} stud_1 ; // while defining union
void main(){
union Student stud_2; // using union keyword
printf("Enter details of stud_1 : \n");
printf("Name : ");
scanf("%s", stud_1.stud_name);
printf("Roll Number : ");
scanf("%d", &stud_1.roll_number);
printf("Percentage : ");
scanf("%f", &stud_1.percentage);
printf("***** Student 1 Details *****\n);
printf("Name of the Student : %s\n", stud_1.stud_name);
printf("Roll Number of the Student : %i\n", stud_1.roll_number);
printf("Percentage of the Student : %f\n", stud_1.percentage);
}
Memory allocation of Union : When the unions are used in the c programming language,
the memory does not allocate on defining union. The memory is allocated when we create the
variable of a particular union. As long as the variable of a union is created no memory is
allocated. The size of memory allocated is equal to the maximum memory required by an
individual member among all members of that union. In the above example program, the
variables stud_1 and stud_2 are allocated with 30 bytes of memory each.
V) Difference between the Structure and Union:

Structure Union
You can use a struct keyword to define a You can use a union keyword to define a
structure. union.
Every member within structure is assigned a In union, a memory location is shared by
unique memory location. all the data members.
Changing the value of one data member
Changing the value of one data member will
will change the value of other data
not affect other data members in structure.
members in union.
It enables you to initialize several members It enables you to initialize only the first
at once. member of union.
The total size of the structure is the sum of The total size of the union is the size of
the size of every data member. the largest data member.
It is mainly used for storing various data It is mainly used for storing one of the
types. many data types that are available.
It occupies space for each and every member It occupies space for a member having the
written in inner parameters. highest size written in inner parameters.
You can access one member at a time in
You can retrieve any member at a time.
the union.
It supports flexible array. It does not support a flexible array.

You might also like