Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
TJNIT 4
-
4.1.1. Introduction
must be called main. Execution of the program will always begin by
carrying-out the instructions in main. Additional functions will be
subordinate to main, and perhaps to one another.
type void), whereas other filnctions return multiple values, with help of
pointers and arguments (e.g.. librarv function scanf).
4.1.3. StandardFunctions
The functions that are inbuilt in the language compiler are library functions. For
example, printf0 and scanf0 belongs to the category of library functions.
These special files are generally supplied with the compiler. The commonly used
filenames are stdio.h, stdlib.h, etc. The suffix "h" denotes a "header" file. This
file has to be included at the beginning of the program.
4.1.4. User-DefinedFunctions
These are actually the user modules that are delibeqately cleated for a specific
purpose. This creation of modules results in function. Various programming
constructs like looping, jumping are used with it.
The main difference between built-in and user-define functions is that library
functions are not required to be written by us whereas a user-defined function has
to be developed by the user at the time of writing a program.
4.1.5. FunctionDefinition
The general form of a function definition in C programming language is as
follows:
Syntax:
return_type function_name(parameter list)
t
body of the function
)
For example, Following is the source code for a function called maxO. This
function takes two parameters numl and num2 and returns the maximum
between the two:
*/
/* function returning the max between two numbers
int max(int numl, int num2)
{
/* local variable declaration */
int result;
if(num1>num2)
result = numl;
else
result = num2;
return result;
)
Explanation: Above function definition tells the compiler that the return type of
the function is int, name of the function is largest, *a- it has three
arguments, all
of type int. The names of argument are not significant.
4.1.7. FunctionArguments
Basically there are two types of function arguments in c:
Function Arguments
4.L.7.1. ActualArguments
Sometimes a function may be called by a portion of a program with some
parameters and these parameters are known as the actual arguments.
For example,
main0
t
int x, y;
4.L.7.2. FormalArguments
The formal arguments are those parameters present in a function definition and it
may also be called as dummy arguments or the parametric variables.
For example,
main0
t
int x, y;
output(x, y);
)
which contains the actual parameters is the operator. The actual parameters
must match the function's formal parameters in type, order and number.
Multiple actual parameters must be separated by commas.
Note:
i) If the actual parameters are more than the formal parameters, the extra actual
arguments will be discarded.
ii) on the other hand, if the actuals are less than the formals, the unmatched
formal arguments will be initialized to some garbage.
iii) Any mismatch in data types may also result in some garbage values.
Argument Conversions
When a function is called, there are a number of possible conversions that will be
applied to the values supplied as arguments depending on the presence or absence
oi a prototype.
The rules mention the default argument promotions and compatible type' Where
they are used, the default argument promotions are:
1) Apply the integral promotions to the value of each argument,
2) lf tie type of the argument is float it is converted to double'
Rules for Conversion
1) At the point of calling a function, if no prototype is in scope, the arguments
all undergo the default argument promotions' Furthermore:
i) If th; number of arguments does not agree with the number of formal
parameters to the function, the behavior is undefined
ii) If the function definition was not a definition containing a prototype, then
the type of the actual arguments after promotion must b-e compatible with
the types of the formal parameters in the definition after they too have
had thi promotions applied. Otherwise the behavior is undefined.
iii) If the function definition was a definition containing a prototype, and the
types of the actual arguments after promotion are not compatible with the
formal parameters in the prototype, then the behavior is undefined. The
behavior is also undefined if the prototype included ellipsis(, ...).
2) At the point of calling a function, if a prototype is in scope, the arguments are
converied, as if by assignment, to the types specified in the prototype' Any
arguments which ialt under the variable argument list category (specified by
the prototype) still undergo the default argument conversions.
The actual arguments must correspond in number, type, and order with formal
arguments specified in the function definition. The actual arguments can be
constants, variables, array names, or expressions.
Hence, when function is called by the call or by value method, it does not affect
the actual contents of the actual arguments. Changes made in the formal
arguments are local to the block of.the called function. Once control returns back
to the calling function the changes made vanish.
Explanation: In the above plogram we are passing values of the actual argument
,x' and 'y' to the function change$. The formal argument 'a' and 'b' of function
change0 receives these values0. The values are interchanged, i.e., value of 'a' is
assigned to 'b' and vice versa and printed. When the control returns back to the
main0, the changes made in function change0 vanishes. In the main0 the values
of ,x' and 'y' are printed as they are read from the keyboard. In call by value
method the formal argument acts as a photocopy of the actual argument. Hence,
changes made in them are temporary.
)
power(x, y)
int x, y;
{
/x body of the function */
/* no values will be transferred back to the caller */
)
)
)
square(n)
int n;
{
int value;
value = n*n;
return(value);
)
One can design similar functions and use in the programs. For example,
int get-number(void);
main
)
int m = get_numbero;
pintf("Vod",m);
)
int get_number(void)
{
int number;
scanf(" Vo {', &number) ;
return(number);
)
Note: indirection operator * in the declaration of sum and diff in the header indicates
these variables are to store addresses, not actual values of variables. Now, the variables
sum and diff point to the memory locations of s and d respectively. Ghe operator * is
known as indirection operator because it gives an indirect reference to a variable
through its address.)
4.2.1. Introduction
In C, the scope of variables can be defined using some storage classes and can
define new type.
Local variables are declared inside a function. These are not known to other
functions outside their own function. In C, local variables are created when the
function is called and destroyed when the functions exit.
Local variables are further divided into auto and static variables.
Gtobal variables declared in main program and are known to all other functions. The
same variable name for global and local variable have the same name then all
reference to that variable name inside the function where the local variables is declared
will refer only to the local variable and will have no effect on the global variable.
1) Auto Storage Class: The auto storage class is the default storage class for all
local variables.
{
I* aato variable declaration*/
int mount;
auto int month;
]
The example above defines two variables with the same storage tlass, auto
can only be used within functions, i.e.,local variables.
2) Register Storage Class: The register storage class is used to define local
variables that should be stored in a regist6r instead of RAM. This means that
the variable has a maximum size equal to the register size (usually one word)
and cannot have the unary '&' operator applied to it (as it does not have a
memory location).
{
/*register variable declaration*1
4) extirn Storage Class: The extern storage class is used to give a reference of
a global variable that is visible to all the program files. When you use
'extern' the variable cannot be initialised as all it does is point the variable
name at a storage location that has been previously defined.
When you have multiple files and you define a global variable or function
which will be used in other files also, then extern will be used in another file
to give reference of defined variable or function. Just for understanding
extern is used to declare a global variable or function in another file.
Program 5: /*Illustrating extern storage class.*/
#include<stdio.h>
#include<conio.h>
int a;
main0
t
extern int b;
pintf("Vod %od",a,b);
getch0;
)
int b=10;
naturally recursive.
/* function prototype */
long int factorial(int n);
main0
t
int n;
long int factorial(int n);
/* read in the integer quantity */
clrscrO;
Printf("n = ";;
scanf("7od", &n);
0utput
Explanation: The main portion of the program simply reads the integer quantity
n and then calls the long-integer recursive function factorial. The function
factorial calls itself recursively, with an actual argument, (n 1) that decreases in
-
magnitude for each successive call. The recursive calls terminate when the value
of the actual argument becomes equal to 1.
The close correspondence between this function and the original problem
definition, in recursive terms, should be readily apparent. In particular, note that
the if-else statement includes a termination condition that beiomes active when
the value of n is less than or equal to 1.
Note: value of n will never be less than 1 unless an improper initial value is
entered into the computer.
When the program is executed, the function factorial will be accessed repeatedly,
once in main and (n - 1) times within itself, though the person using the program
will not be aware of this. only the final answer will be displayed, e.g.:
n= l0
.,s n! = 3628800
when a recursive progr:rm is executed, the recursive function calls are not
executed immediately. Rather, they are placed on a stack until the condition that
terminates the recursion is encountered. * The function calls are then executed in
reverse order, as they are "popped" off the stack. Thus, when evaluating a
factorial recursively, the function calls will proceed in the following order:
n!=nx(n-l)!
(n-1)!=(n-1)x(n-2)!
(n-2)l=(n*2)x(n-3)!
2! =2x l!
The actual values will then be returned in the following reverse order:
1!= 1
2t=2x 1! = 2xI=2
3!=3x21=3x2=6
4!=4 x 3!= 4x6=24
4.4.1. Introduction
location of anothei variable without using variable identifier itself. They are
mainly used in linked lists and call by reference functions'
addresses. It is possible to access and display the memory location of a
variable using '&' operator.
pointer variable and normal variable should be of the,.arrr" type. The pointer
is denoted by '*' symbol.
Figure 4.2 shows another way of representing memory that reinforces the
idea that it is a contiguous array of elements:
00000000 00000000 00000000 00000001 00000000 00000000 000000000 00000010 00000000 00000000
1
I
mal A
Addresses go from low to high
Figure 4.2 also shows the memory initialized with two integer values. The
integer object beginning at address 0 has a value of 1. The second integer
object begins at address 4 and contains the value2.
For example, suppose v is a variable that represents some particular data item.
The compiler will automatically assign memory cells for this data item. The data
item can then be accessed if we know the location (i.e., the address) of the first
memory cell.
Address of v's memory location can be determined by the expression &v, where
& is a unary operator, called the address operator, that evaluates the address ofits
operand.
The data item represented by v (i.e., the data item stored in v's memory cells) can
be accessed by the expression *pv, where * is a unary operator, called the
indirection operator, that operates only on a pointer variable. Therefore, *pv and
v both represent the same data item (i.e., the contents of the same memory cells).
Furthermore, if we write pv = &v and u = *pv, then u and v will both represent
the same value, i.e., the value of v will indirectly be assigned to u. (It is aisumed
that u and v are of the same data type).
4.4.5. Definition
A pointer is a variable that points to another variable. This means that it holds the
memory address of another variable. So we can say that, the pointer does not hold
a value in the traditional sense; instead, it holds the address of another variable. It
points to that other variable by holding its address.
Because a pointer holds an address rather than a value, it has two parts. The
pointer itself holds the address. That addresses points to a value. There is the
pointer and the value pointed to.
For example, consider the following program'
#include<stdio.h>
void main()
t
int i, j;
int *p;/* a pointer to an integer
*/
P=&i:
*P=5;
j = i;
pintf(" %od Vod %od\n", i, j, *P) ;
H
After the line p = &i; the memory situation looks something like this:
Figure 4.4 gives a pictorial view of pointers and memory, where Address: x is
the address of an integer location x:
Address: x
o, I ooa."* I (-.
After compilation, we have the values in the variabres as shown in figure 4.5:
ol "* I Pr addr
^l , I l0
After execution of the first statement, i.e., p - &a; the values of the variables will
be as shown in figure 4.6.
,l " I
.l-,o-l
x x v
v v v
l0 20 .l0
20 20 20
Figure 4.7: (a) Memory status before Assignrnent; (b) Memory Status after
Assign'ment of *p = *q from (ax (c) Memory Status after Assignment of p = q from
*p = *q
Basically the pointers have two types of assignment operations, namely
*p *q,
and p - q, uri *" depicted in figure 4.7. After assignment of = the value
poinied to by the pointer q is copied to the location pointed to by the pointer p,
and both of them have tlie value 20 as shown in figure 4.7. Similarly, after
assignment of p - q, the address stored in the pointer q is copied into the pointer
*p
p. n-ottr the pointers point to the same memory location and hence the value of
and *q is the same, i.e.,20.
Additi6nally. the code initializes the pointer variable piresult to the address of
iresult. We are not initializing *piresult (which would have to be an integer value)
but piresult (which must be an address to an integer)'
Second statement in the preceding listing can be translated into the following two
equivalent statements:
int *piresult;
piresult = &iresulq
4.4.8. IndirectionOperator
An indirection or pointer operator is represented by a combination of asterisk
(*) with a variable.
Syntax: c
int *ptr; ll ptr is a pointer variable which holds the address of an integer data
type.
float *fpointer;
double *dpoint;
char xcpointl:
A pointer variable is dereferenced when the unary operator *, in this case called
the indirection operator, is used as a prefix to the pointer variable or pointer
expression.
The following list includes some of the most common conditions that invalidate a
pointer value.
1) The pointer is a null pointer.
2) The pointer specifies the address of a local item that is not visible at the time
of the reference.
3) The pointer specifies an address that is inappropriately aligned for the type of
the object pointed to.
4) The pointer specifies an address not used by the execuring program.
Any operation performed on the dereferenced pointer directly affects the value of
the variable it points to. For example, consider the following program
Explanation
1) The asterisk (*) used as an indirection operator has a different meaning from
the asterisk used to declare pointer variables:
int *ptr; /* This is a pointer declaration */
xptr = 100; /* The LHS does pointer indirection */
2) Indirection allows the contents of a variable to be accessed and manipulated
without using the name of the variable.
3) All variables that can be accessed directly (by their names) can also be accessed
"trecomes
indirectly by means df pointers. The power of pointers evident in
situations where indirect access is the only';/ay to access variables in memory.
2001 2m2 2003 20/.t4 2005 200,6 2007 2008 2009 2010 2011 2012
cpt cptr+1 cptr+2 cptr+3 cptr+4 :ptr+5 :ptr+6 :pr+7 cptr+8 :ptr+9 ;ptr+10 )ptr+l I
tt r l r
An important point about the pointer variable is that it holds the address of the
very firsl byte of the memory location pointed to by it, known as the base
1 address.
For example, suppose that the address value held by p is 1000. If p is declared as
' a pointer to a 4:byte long int, the 3 in p+3 is multiplied by 4. The value of p+3,
therefore, is 1012. 2
on the other hand, if p is declared as a pointer to a char, p+3 would equal 1003.
In this way, the expression p+3 always means 3 objects after p, regardless of the
type of object that
?points to.
The following arithmetlc opcrations on pointers are not permitted:
i) Addition of nvo pointer variables.
i, Multiplication of a pointer variable by a number.
iii) Division of a pointer variable by a number.
4.4.9.1. Incrementing a Pointer
Generally progralnmers use a pointer in the program instead of an array because
the variable pointer can be incremented, unlike the array name which cannot be
incremented because it is a constant pointer. Following program increments the
variable pointer to access each succeeding element of the a:ray:
Putput ;
ffi c:\usersgrarinsh\DusL*tb\To{#1@ Eiffi
:,ei
"
-ryryJ
main 0
{
int var[] = {10, 100,200};
int i, *ptr;
int mainQ
{
int data[100];
intx p1;
int*p2;
int i;
clrscr0;
for(i=0;i<100;i++)
{
ddta[i]= i;
)
p1 = &data[1J;
p2= &dataf?l;
if(p1>p2)
t
' printf("\n\n pl is greater than p2");
)
else
{
l. printf("\n\n p2 is greater than p1");
)
Any program or data must be loaded into memory before it can be executed or
processed. Therefore, for every program to be executed or data to be processed,
some memory must be allocated for them.
One of the important aspects of pointer is memory allocation. There are two types
memory allocation possible in C.
Memory Allocation
The main drawback of static allocation if there is less number of elements than
then the rest amount of memory is wasted. The concept Dynamic or run time
memory allocation help to overcome this problem.
Dynamically allocated variables are simply variables that do not exist when the
program is loaded, but are created dynamically as they are needed. It is possible,
using these techniques, to create as many variables as needed, use them, and de-
allocate their space for use by other variables.
4.5.2.1. Definition
Process of allocating memory at run time is known as dynamic memory
alloihtion.
Dynamic allocation is a technique in which program can acquire storage space in
the main memory. In this method, the space for the program is allocated from the
free space during execution of the program. The free region of the memory is
called the heap.
The heap changes depend upon what memory model is being used. The amount
of memory requirement is decided by how the program is designed.
Stack
I
High
1
Free memory for
allocation
Global Variables
Low
Program
ptr is a pointer to a memory block which has already been created by mallocQ or
callocO.
4.5.2.2. malloc0Function
ma11oc0 requires one argument - the number of bytes you want to allocate
dynamically. It returns the address of memory chunks that is allotted.
If the memory allocation was successful, malloc0 will return a void pointer - you
can assign this to a pointer variable, which will store the address of the allocated
memory.
If memory allocation failes (e.g if the system is out of memory), mallocQ will
return a NULL pointer.
Passing the pointer into f#b willrelease the allocated memory :n it is good
practice to free memory when its usage is finished.
Program 11:/*illustrating malloc function*/
#include<stdio.h>
#include<conio.h>
main0
i
int tPtr-one;
ptr-one = (int *)malloc(sizeof(int));
if (Ptr-one == 0)
t
Printf("ERROR: Out of memory\n");
return 1;
)
*ptr-one = 25;
printf(" 7od\n', *Ptr-one);
free(ptr-one);
getchO;
Explanation
the size of an
The malloc statement will ask for an amount of memory with
memory available, the malloc
i*g". (32 bits or 4 bytes). If there is not enough
block of memory is
function will return u NUI-1. If the request is granted a
block will be placed into the
allocated (reserved). The address of the reserved
pointer variable'
4.5.2.3. calloc0Function
values stored in
calloc0 is similar to mallocO, but the main difference is that the
the allocated memory space is zeroby default'
callocO Arguments: It requires two arguments. The first is the number of
variables that the programmer would like io allocate memory for. The second is
the size of each variable.
main0
1
int i, n;
int *a;
a - (int*)calloc(n, sizeof(int));
prinfff 'Enter 7od numbers :\n",n) ;
for(i=0;i<n;i++)
{
scanf("Vod" ,&a[i]);
)
printf("The numbers entered are: ");
for(i=0;icn;i++)
{
pintf("Vod, ",a[i]);
)
getch0;
i=jF 4 j
".q
4.5.2.4. realloc0Funcfon
jThe reallocO function ctraniet the size of previously dynamically allocated
memory without changing the pUntents of the memory'
If the done allocation ef memory is not sufficient for the programmer's pse then
there are two ways to again dynamically extend memory'
1) First is to copy "u"iytfring into a larger array, whioh is inefficient, and
Zi Second allocate moie bytes using realloc, without losing data.
reallocO Arguments: realloc {akes two arguments. The first
is the pointer
of bytes that are to be
referencing the memory. The second is the total number
of calling free'
reallocated. Passing ,"- u, the second argument is the equivalent
once again, realloc returns a void pointer if successful, else a NULL pointer is
returned.
automatically
Free() Function: When your program comes out, operating system
good practice when
release all the memory utto"ut"O6y your proglam but as a
memory by
you are not in need of memory anymore then you should release that
calling the function free0.
/* Reallocating memory'*/
str - (char x) realloc(str, 25);
strcat(str, ".com");
printf("StrinE= %os, Address - 7ou\n"' str' str);
free(str);
getcho:
)
C;:\Users\F,ravesh\Desktop\t\<*reck5rcp'exe -
4.5.2.s. Comparison among Memory Allocation Function
Table 4.6: Comparisonof malloc0, ciltocQ and realloc$
Basis malloc0 calloc0 realloc0
No. of I 2 2
Arguments
No. of Bytes Total no. of bytes No. of elements and No. of bytes required
required size of elements for expansion
Type of Type of data unknown Type of data known Dynamic allocation
Data while working in the
code.
Deallocation Free is used explicitly Free is used explicitly realloc itselfcan be
to free the memory to free the memory used for freeing the
memory
In the pass by value is that only direct way to send values from calling function
to called function and it returns processed value through only return statement.
And in pass by reference by passing an address from catting function to called
function and it returns changed data is called function to iie calling function
program.
This concept is also called as pass by reference (address). when we pass
by
address, we are actually passing a pointer to a variable
Program 13
#include<stdio.h>
void swaP (intx, int*);
6 r;l
int main0
{
int a, b;
a= 10;
T""**T
6 =20;
swaP(&a, &b);
Pintf("Vod 7od\n", a, b);
1t
I _l_
)
*Y)
E L+r
+ After t
void swaP (int *x, int
t
int temp;
E L"l
temP = *1; ,.,"nF'l
*x = *y;
pointers
xy = temp; Program. Swap Two Variableg Using
)
swapo function is called using the*.address
operator for the variables that is
required to exchange two values. *
Note: The swap0 function uses two formar parameters
i.e., x and y along with temp local
variable. using the dereferencing the parame^ters,
we perform the swap using the variables
in main and locar variable temp-in swap. rhe complete
working program is shown in the
program above.
4.6.2. FunctionsReturningpointers
A pointer is also a data type in c, we ul.o force a function to return a pointer
t-o the calling function consider the"iprogram
below contains a function to
determine the larger of two numbers. H-ere,
we need a pointer to the rarge of two
variables a and b. Since, *"
1t" using two pointers to a function, which uses a
condition expressiori to determine wniln value is larger.
Once after knowing the larger value,
we can return address of its location
as pointer. The return address is then
assigned in the calling function
pointer p, so that after ;aling the
function it points to either a or b
based on their values. The
corresponding C program and its xy
equivalent diagram of the variable and
Figure 4.10: Function Returning pointers
pointer are shown in figure 4.10.
// function definition
float square ( float x )
t
float p ;
P=x*x;
return(P);
)-
g"tp,rt t'*
tSJ
: es
*f,1 C:Ukers\pravesh\Seskto'p\I*\WU'exe
int sum(int n)
t
int i, j;
j=0;
for(i=1; i<=n; i++)
{
j+=i;
)
returnO;
)
int *q=41.'2'
int *r=&arr[l];
pintf ('\n%o dVo d%o d", arrl2), * (arr+2); * r) ;
pintf('\nVod%o d%o d", * p, * (q+ I ), * (r+ I )) ;
return 0;
)
4) How do you use a pointer to a function?
5) Discuss the various arithmetic operations performed on a pointer.
6) Explain the use of (*) indirection operator?
7) Explain the effect of ++ and
- operator with pointer of all data types?
8) Why addition of two pointers is impossible?
9) Explain the relation between an iuray and a pointer?
10) Distinguish between the address stored in the pointer and the value at that address?
ll) What is the base address? How is it accessed differentially for one-dimensional and two-
dimensional arrays?
12) Explain the comparison of two pointers?
13) Explain the feature ofpointers?
14) How strings are stored using pointer variables? Is it essential to deciare length?
15) Write a program to sort l0 strings with the help of pointers.