Sie sind auf Seite 1von 34

UNIT II FUNCTIONS, POINTERS, STRUCUTRES AND UNIONS

Functions-Pass by value - Pass by reference - Recursion-Pointers-Definition-


Initialization-Pointers Arithmetic. Structures and unions-definition-Structure within a
structure-Union-Programs using structures and Unions-Storage classes, Pre-processor
directives.
FUNCTION
 A function is a block of code that performs a particular task.
 A function is a sub-program that contains one or more statements and it performs some task when
called.

 C language provides an approach in which you need to declare and define a group of
statements once and that can be called and used whenever required. This saves both time
and space.
C functions can be classified into two categories:

Library functions:
 Library functions are those functions which are defined by C library, example printf(),
scanf(), strcat() etc.
 You just need to include appropriate header files to use these functions. These are
already declared and defined in C libraries.
 User-defined functions are those functions which are defined by the user at the time
of writing program.
 Functions are made for code reusability and for saving time and space.
Benefits of Using Functions:
1. It provides modularity to the program.
2. Easy code Reusability. You just have to call the function by its name to use it.
3. In case of large programs with thousands of code lines, debugging and editing becomes easier
if you use functions.

Function declaration:
General syntax of function declaration is,
return-type function-name (parameter-list) ;

 Like variable and an array, a function must also be declared before its called.
 A function declaration tells the compiler about a function name and how to call the
function.
 The actual body of the function can be defined separately.

A function declaration consists of 4 parts:


 return-type
 function name
 parameter list
 Terminating semicolon.

Function definition Syntax


General syntax of function definition is,
return-type function-name (parameter-list)
{
function-body ;
}
The first line return-type function-name(parameter) is known as function header and the
statement within curly braces is called function body.

Return-type:
 return type specifies the type of value(int,float,char,double) that function is expected to
return to the program calling the function.

Function-name:

 function name specifies the name of the function.


 The function name is any valid C identifier and therefore must follow the same rule of
formation as other variables in C.

Parameter-list:

 The parameter list declares the variables that will receive the data sent by calling
program.
 They often referred to as formal parameters.
 These parameters are also used to send values to calling program.

Function-body:

 The function body contains the declarations and the statement(algorithm) necessary for
performing the required task.
 The body is enclosed within curly braces { } and consists of three parts.

Local variable declaration:

 function statement that performs the tasks of the function.


 a return statement that return the value evaluated by the function.

Functions and Arguments:


 Arguments are the values specified during the function call, for which the formal
parameters are declared in the function.

FUNCTION PARAMETERS

Actual Parameter

These are the parameters transferred from the calling function to the called function.

Formal Parameter

These are the parameters which are used in the called function.

• The return statement may or may not send some values to the calling function.

• Syntax:

return; (or)

return(expression);

FUNCTION PROTOTYPES
1. Function with no arguments and no return values.

2. Function with arguments and no return values.

3. Function with arguments and return values.

4. Function with no arguments and with return values.

1. Function with no arguments and no return values:

 Here no data transfer take place between the calling function and the called function.

 These functions act independently, i.e. they get input and display output in the same block.

Example Program:

#include <stdio.h>

#include<conio.h>

void main()

{ void add(void);

add();

void add()

int a,b,c;

printf("\nEnter two number:");

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

c=a+b;

printf("\nSum is:%d",c);

2. Function with arguments and no return values:


 Here data transfer take place between the calling function and the called function.

 It is a one way data communication, i.e. the called program receives data from calling program
but it does not return any value to the calling program.

Example Program:

#include <stdio.h>

#include<conio.h>

Void main()

int a,b;

void add(int,int);

printf("\nEnter two number:");

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

add(a,b);

void add(int x,int y) //function with arguments

int z;

z=x+y;

printf("\nSum is:%d",z);

3. Function with arguments and return values:

 Here data transfer take place between the calling function and the called function as well as
between called function and calling function.

 It is a two way data communication, i.e. the called program receives data from calling
program and it return some value to the calling program.

Example Program:

#include <stdio.h>

#include<conio.h>

void main()
{ int a,b,c;

int add(int,int);

printf("\nEnter two number:");

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

c=add(a,b);

printf("\nSum is:%d",c); }

int add(int x,int y)

int z;

z=x+y;

return(z);

4. Function with no arguments and with return values:

 Here data transfer take place between the called function and the calling function.

 It is a one way data communication, i.e. the called program does not receives data from calling
program but it return some value to the calling program.

#include <stdio.h>

#include<conio.h>

void main()

{ int add(),d;

d=add();

printf("\nSum is:%d",d);}

int add() //function with no argument

{ int a,b,c;

printf("\nEnter two number:");

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

c=a+b;

return(c); }

NESTING OF FUNCTIONS:
 C language also allows nesting of functions, one function using another function inside
its body.
 We must be careful while using nested functions, because it may lead to infinte nesting.
function1()
{
function2() ;
//statements
}
 If function2 calls function1 inside it, then in this case it will lead to infinite nesting, they
will keep calling each other.
 Hence we must be careful.
1. CALL/PASS BY VALUE

 Actual argument passed to the formal argument.

 Any changes to the formal argument do not affect the actual argument.

void main()
{
int x,y,change(int,int);
printf("\nEnter value of x:");
scanf("%d",&x);
printf("\nEnter value of y:");
scanf("%d",&y);
change(x,y);
printf("\n\nValues in the Main()-->x=%d,y=%d",x,y);
}
int change(int a,int b)
{
int c;
c=a;
a=b;
b=c;
printf("\nValues in the Fuction -->x=%d,y=%d",a,b);
}
Output:
Enter value of x:5
Enter value of y:6
Values in the Fuction -->x=6,y=5
Values in the Main()-->x=5,y=6

2. CALL / PASS BY REFERENCE:


 Instead of passing value, the address of the argument will be passed.

 Any changes to the formal argument will affect the actual argument.

#include <stdio.h>

#include<conio.h>

void main()

int x,y,change(int*,int*);

printf("\nEnter value of x:");

scanf("%d",&x);

printf("\nEnter value of y:");

scanf("%d",&y);

change(&x,&y);

printf("\n\nValues in the Main()-->x=%d,y=%d",x,y);

int change(int *a,int *b)

int c;

c=*a;

*a=*b;

*b=c;

printf("\nValues in the Function -->x=%d,y=%d",*a,*b);

Output:
Enter value of x:5
Enter value of y:6
Values in the Function -->x=6,y=5
Values in the Main()-->x=6,y=5
RECURSION:
 Recursion is a special type of nesting functions, where a function calls itself inside it.
 We must have certain condition to break out of the recursion, otherwise recursion is
infinite.

function1()
{
function1() ;
//statements
}

Factorial of a number using Recursion

int factorial(int x);


void main()
{
int a,b;
clrscr();
printf("Enter no.");
scanf("%d",&a);
b=factorial(a);
printf("%d",b);
getch();
}
int factorial(int x)
{
int r=1;
if(x==1) return 1;
else r=x*factorial(x-1);
return r;
}

POINTERS:

 Pointers are variables that contain memory addresses as their values.


 A variable name directly references a value.

 A pointer indirectly references a value. Referencing a value through a pointer is called


indirection.

 A pointer variable must be declared before it can be used.

Examples of pointer declarations:

FILE *fptr;

int *a;

float *b;

char *c;

 The asterisk, when used as above in the declaration, tells the compiler that the variable is
to be a pointer, and the type of data that the pointer points to, but NOT the name of the
variable pointed to.

Use of & and *:

 When is & used?

& -- "address operator" which gives or produces the memory address of a data
variable

 When is * used?

*-- "dereferencing operator" which provides the contents in the memory location
specified by a pointer
Consider the statements:

int main ( )
{
FILE *fptr1 , *fptr2 ; /* Declare two file pointers */
int *aptr ; /* Declare a pointer to an int */
float *bptr ; /* Declare a pointer to a float */
int a ; /* Declare an int variable */
float b ; /* Declare a float variable */
aptr = &a ;
bptr = &b ;
fptr2 = fopen ( "my_out.dat" , "w" ) ;
fptr1 = fopen ( "my_in.dat" , "r" ) ;
if ( fptr1 != NULL )
{
fscanf (fptr1, "%d%f", aptr, bptr);
fprintf (fptr2, "%d %d\n", aptr, bptr ) ;
fprintf (fptr2, "%d %f\n", *aptr, *bptr ) ;
fprintf (fptr2, "%d %f\n", a, b);
fprintf (fptr2, "%d %d\n", &a , &b ) ;
return 0 ;
}}
OUTPUT:
/* input file */
5 6.75
/* output file */
1659178974 1659178976
5 6.750000
5 6.750000
1659178974 1659178976
POINTERS AND FUNCTIONS:

 Pointers can be used to pass addresses of variables to called functions, thus allowing the
called function to alter the values stored there.
 We looked earlier at a swap function that did not change the values stored in the main
program because only the values were passed to the function swap.

 This is known as "call by value".

 If instead of passing the values of the variables to the called function, we pass their
addresses, so that the called function can change the values stored in the calling routine.
This is known as "call by reference" since we are referencing the variables.

 The following shows the swap function modified from a "call by value" to a "call by
reference". Note that the values are now actually swapped when the control is returned to
main function.

void swap ( int *a, int *b ) ;


int main ( )
{
int a = 5, b = 6;
printf("a=%d b=%d\n",a,b) ;
swap (&a, &b) ;
printf("a=%d b=%d\n",a,b) ;
return 0 ;
}
void swap( int *a, int *b )
{
int temp;
temp= *a;
*a= *b;
*b = temp ;
printf ("a=%d b=%d\n", *a, *b);}
Results:
a=5 b=6
a=6 b=5
a=6 b=5
ARITHMETIC AND LOGICAL OPERATIONS ON POINTERS:

 A pointer may be incremented or decremented


 An integer may be added to or subtracted from a pointer.
 Pointer variables may be subtracted from one another.
 Pointer variables can be used in comparisons, but usually only in a comparison to NULL.
When an integer is added to or subtracted from a pointer, the new pointer value is changed by the
integer times the number of bytes in the data variable the pointer is pointing to.

For example,

if the pointer valptr contains the address of a double precision variable and that address is
234567870, then the statement:

valptr = valptr + 2;

would change valptr to 234567886

NULL POINTER:

 It is always a good practice to assign a NULL value to a pointer in case you do


not have an exact address to be assigned.
 This is done at the time of variable declaration.
 A pointer that is assigned NULL is called a null pointer.
 The NULL pointer is a constant with a value of zero defined in several standard
libraries.

Consider the following program

#include <stdio.h>

int main () {

int *ptr = NULL;

printf("The value of ptr is : %x\n", ptr );

return 0;

When the above code is compiled and executed, it produces the following result −

The value of ptr is 0

DANGLING POINTER:
If any pointer is pointing the memory address of any variable but after some variable has
deleted from that memory location while pointer is still pointing such memory location. Such
pointer is known as dangling pointer and this problem is known as dangling pointer problem.

Example:

#include<stdlib.h>
{
char *ptr = malloc(Constant_Value);
.......
.......
.......
free (ptr); /* ptr now becomes a dangling pointer */
}

 We have declared the character pointer in the first step.

 After execution of some statements we have de-allocated memory which is allocated


previously for the pointer.

 As soon as memory is de-allocated for pointer, pointer becomes dangling pointer

How to ensure that Pointer is no Longer Dangling?

#include<stdlib.h>
{
char *ptr = malloc(Constant_Value);
.......
.......
.......
free (ptr); /* ptr now becomes a dangling pointer */
ptr = NULL /* ptr is no more dangling pointer */

NOTE:

 After de-allocating memory, initialize pointer to NULL so that pointer will be no longer
dangling.

 Assigning NULL value means pointer is not pointing to any memory location
STRUCTURE:
 Structure is the collection of variables of different types under a single name for
better handling
NEED FOR STRUCTURE DATA TYPE:

 When programming, it is often convenient to have a single name with which to refer to a
group of a related values.
 Structures provide a way of storing many different values in variables of potentially
different types under the same name.
 This makes it a more modular program, which is easier to modify because its design
makes things more compact.
 Structs are generally useful whenever a lot of data needs to be grouped together --for
instance, they can be used to hold records from a database or to store information about
contacts in an address book.
STRUCTURE DEFINITION IN C

 Keyword struct is used for creating a structure.


Syntax of structure:

struct structure_name

data_type member1;

data_type member2;

data_type memeber;

};

struct person

{
Example:char name[50];

int cit_no;

float salary;

};
STRUCTURE VARIABLE DECLARATION:

 When a structure is defined, it creates a user-defined type but, no storage is allocated.


 For the above structure of person, variable can be declared as:

struct person

char name[50];

int cit_no;

float salary;

};

Inside main function:

struct person p1, p2, p[20];

Another way of creating structure variable is:


struct person

char name[50];

int cit_no;

float salary;

}p1 ,p2 ,p[20];

 In both cases,2 variables p1, p2 and array p having 20 elements of type struct person are
created.
ACCESSING MEMBERS OF A STRUCTURE:

There are two types of operators used for accessing members of a structure.

 Member operator (.)


 Structure pointer operator(->)
Any member of a structure can be accessed as:

.
structure_variable_name member_name

Suppose, we want to access salary for variable p2. Then, it can be accessed as:

p2.salary

KEYWORD TYPEDEF WHILE USING STRUCTURE:


 Programmer generally uses typedef while using structure in C language.
For example:

typedef struct complex{

int imag;

float real;

}comp;

Inside main:

comp c1,c2;

 Here, typedef keyword is used in creating a type comp(which is of type as struct complex).
 Then, two structure variables c1 and c2 are created by this comp type.
EMPLOYEE PAYROLL USING STRUCTURE

#include<stdio.h>
#include<conio.h>
struct employee
{
char name[20];
int empno;
float bsal;
float net;
};
void main()
{
struct employee emp;
float hra,da,det;
clrscr();
printf("\nEmployee Details");
printf("\nEnter the employee name");
scanf("%s",emp.name);
printf("\nEnter the employee no");
scanf("%d",&emp.empno);
printf("\nEnter the basic salary");
scanf("%f",&emp.bsal);
hra=((15*emp.bsal)/100);
da=((10*emp.bsal)/100);
det=((5*emp.bsal)/100);
emp.net=emp.bsal+hra+da-det;
printf("\nEmployee name:%s",emp.name);
printf("\nEmployee no:%d",emp.empno);
printf("\nEmployee Basic salary:%f",emp.bsal);
printf("\nHRA:%f",hra);
printf("\nDA:%f",da);
printf("\nDetection:%f",det);
printf("\nGross salary:%f",emp.net);
getch();
}
Output:
Employee Details
Enter the employee name lakshmi
Enter the employee no11
Enter the basic salary12000
Employee name:lakshmi
Employee no:11
Employee Basic salary:12000.000000
HRA:1800.000000
DA:1200.000000
Detection:600.000000
Gross salary:14400.000000
NESTED STRUCTURE IN C
 Nested structure in C is nothing but 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.

struct date
{
int date;
int month;
int year;
};

struct Employee
{
char ename[20];
int ssn;
float salary;
struct date doj;
}emp1;

Accessing Nested Elements:


1. Structure members are accessed using dot operator.
2. ‘date‘ structure is nested within Employee Structure.
3. Members of the ‘date‘ can be accessed using ‘employee’
4. emp1 & doj are two structure names (Variables)

Explanation Of Nested Structure:


Accessing Month Field : emp1.doj.month
Accessing day Field : emp1.doj.day
Accessing year
struct Field : emp1.doj.year
Employee
{
char ename[20];
int ssn;
Way 2: Declare embedded structures
float salary;
struct date
{
int date;
int month;
int year;
}doj;
}emp1;
Accessing Nested Members:
Accessing Month Field : emp1.doj.month
Accessing day Field : emp1.doj.day
Accessing year Field : emp1.doj.year
Live Complete Example:

#include <stdio.h>
struct Employee
{
char ename[20];
int ssn;
float salary;
struct date
{
int date;
int month;
int year;
}doj;
}emp = {"Pritesh",1000,1000.50,{22,6,1990}};
int main(int argc, char *argv[])
{
printf("\nEmployee Name : %s",emp.ename);
printf("\nEmployee SSN : %d",emp.ssn);
printf("\nEmployee Salary : %f",emp.salary);
printf("\nEmployee DOJ : %d/%d/%d", emp.doj.date,emp.doj.month,emp.doj.year);

return 0;
Output :
}
Employee Name : Pritesh
Employee SSN : 1000
Employee Salary : 1000.500000
Employee DOJ : 22/6/1990
UNION:
 Union is user defined data type used to stored data under unique variable name at single memory
location.

 Union is similar to that of structure.

 Syntax of union is similar to structure. But the major difference between structure and union is
'storage.'

 In structures, each member has its own storage location, whereas all the members of union use
the same location.

 Union contains many members of different types; it can handle only one member at a time.

 To declare union data type, 'union' keyword is used.

 Union holds value for one data type which requires larger storage among their members.

Syntax

union union_name

<data-type> element 1;

<data-type> element 2;

<data-type> element 3;

}union_variable;

MEMORY ALLOCATION
Example:

union techno

int id;

char nm[50];

}tch;

void main()

clrscr();

printf("\n\t Enter developer id : ");

scanf("%d", &tch.id);

printf("\n\n\t Enter developer name : ");

scanf("%s", tch.nm);

printf("\n\n Developer ID : %d", tch.id);//Garbage

printf("\n\n Developed By : %s", tch.nm);

getch();
DIFFERENCE BETWEEN STRUCTURE AND UNION

STRUCTURE UNION

1.The keyword struct is used to define a structure 1. The keyword union is used to define a union.
2. 2.
 When a variable is associated with a  When a variable is associated with a union,
structure, the compiler allocates the compiler allocates the memory by
the memory for each member. considering the size of the largest memory.

 The size of structure is greater than or equal  So, size of union is equal to the size of largest
to the sum of sizes of its members. member.

 The smaller members may end with unused


slack bytes.
3. Each member within a structure is assigned 3. Memory allocated is shared by individual members
unique storage area of location. of union.

4. The address of each member will be in ascending 4. The address is same for all the members of a union.
order This indicates that memory for each member This indicates that every member begins at the same
will start at different offset values. offset value.

5 Altering the value of a member will not affect 5. Altering the value of any of the member will alter
other members of the structure. other member values.

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

7. Several members of a structure can initialize at 7. Only the first member of a union can be initialized.
once.
Struct stu Struct emp
{ {
Int a; Int a;
Char b; Char b;
Float c; Float c;
} }

Size of stu is 7 bytes. Size of union emp is 4 bytes.

PROGRAM USING STRUCTURE AND UNION:


1. Difference between union and structure.

#include <stdio.h>
union unionJob
{
//defining a union
char name[32];
float salary;
int workerNo;
} uJob;

struct structJob
{
char name[32];
float salary;
int workerNo;
} sJob;

int main()
{
printf("size of union = %d", sizeof(uJob));
printf("\nsize of structure = %d", sizeof(sJob));
return 0;
}
Output
size of union = 32
size of structure = 40

2. Passing structure in function and returning structure from function program in C


#include <stdio.h>
struct FirstStruct
{
int Num1;
int Num2;
}FirstStruct_IP;
//function declarations
struct FirstStruct TakeUserInput(void);
void DisplayOutput(struct FirstStruct Input);
//structure object declaration
struct FirstStruct inputStruct;
int main()
{
//create a structure to get a return from TakeUserInput function
//Now use the DisplayOutput to print the input
DisplayOutput(TakeUserInput());
return 0;
}
//This function returns a structure after storing the user input into it
struct FirstStruct TakeUserInput(void)
{
printf("Enter a number: ");
scanf("%d",&inputStruct.Num1);
printf("Enter a number again: ");
scanf("%d",&inputStruct.Num2);
return inputStruct;
}
//Function taking Structure as argument
void DisplayOutput(struct FirstStruct Input)
{
printf("%d\n",((Input.Num1)+(Input.Num2)));
}

OUTPUT:

Enter a number: 10
Enter a number again: 20
30
3. Union program

#include <stdio.h>

main ()
{
union id {
char name[40];
int number;
};
struct {
int salary;
union id description;
} student,faculty;

printf("%d\n", sizeof(union id));


student.description.name ="Sam";
printf("%s %d\n",
student.description.name,student.description.number);
student.description.number = 12;
printf("%s %d\n",
student.description.name,student.description.number);

}
DYNAMIC MEMORY ALLOCATION

FUNCTION USE OF FUNCTION

Allocates requested size of bytes and returns a pointer first byte of allocated
malloc() space
Allocates space for an array elements, initializes to zero and then returns a
calloc() pointer to memory
free() dellocate the previously allocated space
realloc() Change the size of previously allocated space

malloc():
 The name malloc stands for "memory allocation".
 The function malloc() reserves a block of memory of specified size and return a
pointer of type void which can be casted into pointer of any form.

Syntax of malloc()

ptr=(cast-type*)malloc(byte-size)

 Here, ptr is pointer of cast-type.


 The malloc() function returns a pointer to an area of memory with size of byte
size.
 If the space is insufficient, allocation fails and returns NULL pointer.

ptr=(int*)malloc(100*sizeof(int));

This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes
respectively and the pointer points to the address of first byte of memory.

calloc()
 The name calloc stands for "contiguous allocation".
 The only difference between malloc() and calloc() is that, malloc() allocates
single block of memory whereas calloc() allocates multiple blocks of memory
each of same size and sets all bytes to zero.

Syntax of calloc()

ptr=(cast-type*)calloc(n,element-size);

This statement will allocate contiguous space in memory for an array of n elements.

For example:

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

 This statement allocates contiguous space in memory for an array of 25 elements


each of size of float, i.e, 4 bytes.

free():
 Dynamically allocated memory with either calloc() or malloc() does not get
return on its own.
 The programmer must use free() explicitly to release space.

syntax of free()

free(ptr);

realloc():
 If the previously allocated memory is insufficient or more than sufficient.

 Then, you can change memory size previously allocated using realloc().

Syntax of realloc()

ptr=realloc(ptr,newsize);

PREPROCESSOR
 It is a program that processes the source program before compilation.
 It operates under the following directives
– File Inclusion
– Macro substitution
– Conditional inclusion
File Inclusion
• It is used to include some file that contains functions or some definitions.
• Syntax:
#include<filename> (or)
#include“filename”
• Eg: #include<stdio.h>
#include “ex.c”
Example
#include<stdio.h>
#include<conio.h>
#include "addition.txt"
void main()
{
int a,b;
printf("\nEnter the numbers:");
scanf("%d%d",&a,&b);
printf("The Value is %d",add(a,b));
getch();
}
addition.txt
int add(int a,int b)
{
return(a+b);
}
Output
Enter the numbers:7
4
The Value is 11

Macro Substitution
• It is used to define and use integer, string, or identifier in the source program
• The three forms of macros are
– Simple Macro
– Argumented Macro
– Nested Macro
Simple Macro
• It is used to define some constants
• Syntax
# define identifier string/integer
• Eg:
#define pi 3.14
#define CITY “chennai”
Example
#include<stdio.h>
#include<conio.h>
#define pi 3.14
#define CITY "chennai"
void main()
{
printf("The Value is %f",2*pi);
printf("\nThe Value CITY is %s",CITY);
getch();
}

Output:
The Value is 6.280000
The Value CITY is chennai

Argumented Macro
• It is used to define some complex forms in the source program.
• Syntax:
#define identifier (v1,v2,….) string/integer
• Eg:
#define cube(n) (n*n*n)
Example
#include<stdio.h>
#include<conio.h>
#define cube(n) (n*n*n)
void main()
{
printf("The Value of 3 cube is %d",cube(3));
getch();
}
Output:
The Value of 3 cube is 27
Nested Macro
• Here one macro is used by another macro.
• Eg:
#define a 3
#define sq a*a
Example
#include<stdio.h>
#include<conio.h>
#define a 3
#define sq a*a
void main()
{
printf("The Value is %d",sq);
getch();
}
Output:
The Value is 9

Conditional Inclusion
• It is used to include some conditional statements.
Example
#include<stdio.h>
#include<conio.h>
#define a 3
#ifdef a
#define c a+5
#endif
void main()
{
printf("\nThe value C is %d",c);
getch();
}
Output:
The value C is 8

Das könnte Ihnen auch gefallen