0% found this document useful (0 votes)
14 views39 pages

PPS Unit - IV

Pps programming c language

Uploaded by

hajera7779
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)
14 views39 pages

PPS Unit - IV

Pps programming c language

Uploaded by

hajera7779
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/ 39

Subject: PPS Unit – III

UNIT - IV
Pointers - Introduction, Pointers for Inter-Function Communication, Pointers to Pointers, Compatibility,
L -value and R-value, Arrays and Pointers, Pointer Arithmetic and Arrays, Passing an Array to a
Function, Memory Allocation Functions, Array of Pointers, Programming Applications, Pointers to
void, Pointers to Functions, Command-line Arguments.
Strings - Concepts, C Strings, String Input / Output Functions, Arrays of Strings, String Manipulation
Functions
------------------------------------------------------------------------------------------------------------------------------
Introduction
A pointer is a constant or a variable that contains the address of another variable.
Computers use their memory for storing the instructions of a program and values of the variables that
are associated with it. The computer‟s memory is a sequential collection of “storage cells”, commonly
known as a byte, has a number called address associated with it. Typically, the addresses are numbered
consecutively, starting from 0. The last address depends on the memory size. A computer system having
64k memory will have its last address as 65,535

1
Subject: PPS Unit – III

Whenever a variable is declared, the system allocates an appropriate location to hold the value of the
variable. Since every byte has a unique address, this location will have its own address.
Example: int x=200;
This instructs the system to find a location for the integer variable x and puts the value 200 in it. Assume
the system has chosen the address location 4000 for x. it is represented as below.

X Name of variable
200 Value of variable

4000 Address of variable

Since memory addresses are simply numbers, they can be assigned to some variables which can be
stored in memory, like any other variable. Such variables that hold memory addresses are called
pointers.
A Pointer is a variable that contains an address which is a location of another variable in memory.
Since pointer is a variable, its value is also stored in the memory in another memory location.
Suppose the address of „quantity‟ is assigned to a variable „p‟. The link between the variables „p‟ and
„quantity‟ can be visualized as shown below
Example: int quantity = 179
P=& quantity

Variable name Value Address

179
Quantity 500

500
P 5050

Example of pointer variable

Since the value of „p‟ is the address of „quantity‟, we may access the value of quantity by using the
value of „p‟. Therefore, the variable „p‟ points to the variable „quantity‟. Thus „p‟ gets the name pointer.
Operators used in pointer:
There are two basic operators used with pointers
1. The address operator: &(ampersand, address of )
2. The indirection operator: *(asterisk, dereferencing, indirection operator)

2
Subject: PPS Unit – III

An address operator gives the address of a variable, while the indirection operator gives the value of the
variable that the pointer is pointing to.
Accessing the Address of a Variable
The actual location of a variable in the memory is system dependent. Therefore, the address of a variable
is not known to us immediately. The address of a variable can be determined with the help of the address
(&) operator available in „C‟. The use of this address (&) operator we have already discussed in the
“scanf()” function. The address (&) operator immediately preceding a variable returns the address
of the variable associated with it.
Example: p=&quantity;
Would assign the address 500 (the location of „quantity‟) to the variable „p‟. The address (&) operator
can be called as „address of‟. The address (&) operator can be used only with a simple variable or an
array element.
If „x‟ is an array, then expressions such as &x[0]
&x[i+3]
are valid and represent addresses of 0th and (i+3)th elements of x.
Features of Pointers:
 Pointers save memory space.
 Execution time with pointers is faster because data are manipulated with the address, that is, direct
access to memory location.
 Memory is accessed efficiently with the pointers. The pointer assigns and releases the memory as
well. Hence it can be said the Memory of pointers is dynamically allocated.
 Pointers are used with data structures. They are useful for representing two-dimensional and multi-
dimensional arrays.
 An array, of any type, can be accessed with the help of pointers, without considering its subscript
range.
 Pointers are used for file handling.
 Pointers are used to allocate memory dynamically.
Pointer Definition:
Pointer is the derived data type of C. The pointer is a variable which stores the address of another
variable. This variable can be of type int, char, array, function, or any other pointer.

3
Subject: PPS Unit – III

Declaration of Pointers:
Just like the variables, we also have to declare the pointers in C before we use them in any program. We
can name these pointers anything that we like, as long as they abide by the naming rules of the C
language.
The syntax to declaration a pointer variable is:
data_type *name_of_pointer_variable;
Note: This tells the compiler three things about the variable name_of_pointer_variable
1. The asterisk (*) tells that the variable name_of_pointer_variable is a pointer variable
2. name_of_pointer_variable needs a memory location
3. name_of_pointer_variable points to a variable of type data_type .
Example: int *p;
The above declaration tells that the variable „p‟ as a pointer variable that points to an integer data-
type. The type „int‟ refers to the data-type of the variable being pointed to by „p‟ and not the type of
the value of the pointer.
Example: float *x;
The above declaration tells that the variable „x‟ as a pointer to a floating point variable.
Initialization of Pointer
Once we declare a pointer, we then initialize it just like the standard (fundamental type) variables using
an address of the variable. In case we don‟t initialize the pointers in the program and start using it
directly, the results can be unpredictable and potentially disastrous.
We use the address „&‟ (ampersand) operator to get the variable‟s address in the program. We place the
address „&‟ (ampersand) operator just before that variable‟s name whose address we require.
The syntax to initialize a pointer is:
pointer-variable-name = &variable-name;
Example: p=&quantity;
Which causes „p‟ to point to „quantity‟ i.e. „p‟ now contains the address of „quantity‟. This is known as
pointer initialization.
Note: Before a pointer is initialized, it should not be used.
Pointer variables always point to the corresponding type of data.
Example: int a,b;
int *p;
p=&a;
b=*p;
4
Subject: PPS Unit – III

Note: Assigning an absolute address to a pointer variable is prohibited or invalid.


int *ptr;
ptr=5368; are invalid
A pointer variable can be initialized in its declaration itself as shown be,
Example: int x,*p=&x; are valid
It declares „x‟ as an integer variable and „p‟ as a pointer variable and then initializes „p‟ to the address of
„x‟. Pointers should be initialized either when they are declared or in an assignment statement.
A pointer may be initialized to 0, NULL or an address of a variable.
Example Program-1 to demonstrate pointer variable
#include <stdio.h>
int main()
{
int a,*p; // declaring the variable and pointer
a = 10; // initializing variable 'a'
p = &a; // initializing the pointer

printf("%d",a); //this will print the value of 'a'

printf("%d",*p); //this will also print the value of 'a'.


//Here in *p, * is indirection operator which
//will return the value of variable a.

printf("%u",p); //this will print the address of 'a'

printf("%u",&a); //this will also print the address of 'a'

printf("%u",&p); //this will print the address of 'p'


}
Example Program-2: program for pointer (Referencing and dereferencing) */
#include<stdio.h>
int main()
{
int a,b; // declaring the variables “a” and “b”
int *p; // declaring pointer variable “p”
a=100 // initializing variable 'a'
p=&a; // initializing the pointer
printf(“%d\n”,p); //this will print the address of 'a'
printf(“%d\n”,*p); //this will print the value of 'a'
printf(“%d\n”,a); //this will also print the address of 'a'
5
Subject: PPS Unit – III

printf(“%d\n”,&a); //this will print the address of 'a'


*p=200; // this will store the value 200 at variable „a‟
printf(“%d\n”,a); //this will print the value of 'a' and now it is 200
b=*p; //this will assign the value of „a‟ to b
printf(“%d\n”,b); //this will print the value of 'b'
}
Points to remember while using pointers:
1. While declaring / initializing the pointer variable, * indicates that the variable is a pointer.
2. The address of any variable is given by preceding the variable name with Ampersand (&).
3. The pointer variable stores the address of a variable. The declaration “ int *a ” doesn't mean that „a‟
is going to contain an integer value. It means that „a‟ is going to contain the address of a variable
storing value of type integer.
4. To access the value of a certain address stored by a pointer variable, * (indirection operator) is used.
Here, the * can be read as 'value at'.
Types of Pointers in C
Pointers in C can be classified into many different types based on the parameter on which we are
defining their types. If we consider the type of variable stored in the memory location pointed by the
pointer, then the pointers can be classified into the following types:
1. Integer Pointers
As the name suggests, these are the pointers that point to the integer values.
Syntax: int *ptr;
These pointers are pronounced as Pointer to Integer.
Similarly, a pointer can point to any primitive data type. It can also point to derived data types such as
arrays and user-defined data types such as structures.
2. Array Pointer
Pointers and Array are closely related to each other. Even the array name is the pointer to its first
element. They are also known as Pointer to Arrays. We can create a pointer to an array using the given
syntax.
Syntax: char *ptr = &array_name;
3. Structure Pointer
The pointer pointing to the structure type is called Structure Pointer or Pointer to Structure. It can be
declared in the same way as we declare the other primitive data types.
Syntax: struct struct_name *ptr;
In C, structure pointers are used in data structures such as linked lists, trees, etc.
6
Subject: PPS Unit – III

4. Function Pointers
Function pointers point to the functions. They are different from the rest of the pointers in the sense that
instead of pointing to the data, they point to the code.
Consider a function prototype – int func (int, char), the function pointer for this function will be
Syntax: int (*ptr)(int, char);
Note: The syntax of the function pointers changes according to the function prototype.
5. Double Pointers
In C language, we can define a pointer that stores the memory address of another pointer. Such pointers
are called double-pointers or pointers-to-pointer. Instead of pointing to a data value, they point to
another pointer.
Syntax: data-type ** pointer_name;
Dereferencing Double Pointer
*pointer_name; // get the address stored in the inner level pointer
**pointer_name; // get the value pointed by inner level pointer
Note: In C, we can create multi-level pointers with any number of levels as shown below
***ptr3, ****ptr4, ******ptr5 and so on.
6. NULL Pointer
The Null Pointers are those pointers that do not point to any memory location. They can be created by
assigning a NULL value to the pointer. A pointer of any type can be assigned the NULL value.
Syntax: data_type *pointer_name = NULL;
or
pointer_name = NULL
It is said to be good practice to assign NULL to the pointers currently not in use.
7. Void Pointer
The Void pointers in C are the pointers of type void. It means that they do not have any associated data
type. They are also called generic pointers as they can point to any type and can be type casted to any
type.
Syntax: void * pointer_name;
Note: One of the main properties of void pointers is that they cannot be dereferenced.
8. Wild Pointers
The Wild Pointers are pointers that have not been initialized with something yet. These types of C-
pointers can cause problems in our programs and can eventually cause them to crash. If values are
updated using wild pointers, they could cause data abort or data corruption.
7
Subject: PPS Unit – III

Example
int *ptr;
char *str;
9. Constant Pointers
In constant pointers, the memory address stored inside the pointer is constant and cannot be modified
once it is defined. It will always point to the same memory address.
Syntax: data_type * const pointer_name;
10. Pointer to Constant
The pointers pointing to a constant value that cannot be modified are called pointers to a constant. Here
we can only access the data pointed by the pointer, but cannot modify it.
Syntax: const data_type * pointer_name;
Pointers for Inter-Function Communication
One of the most useful applications of pointers is in functions. When we discussed functions in
the unit – 2, we saw that C uses the pass-by-value for upward, bi-directional communication, the only
direct way to send something back to the calling function from a called function is through the return
statement.
We also saw that we can use upward and bi-directional communication by passing an address
and using it to refer back to data in the calling program. When we pass an address, we are actually
passing a pointer to a variable. Hence when we need to send more than one value back from a
function, we use pointers. We use either upward or bi-directional communication to send any number
of variables to the calling function.

/* Program which returns multiple values to calling function pointer using pointer variable */
#include <stdio.h>
void compare(int a, int b, int* add_great, int* add_small)
{
if (a > b)
{
// a is stored in the address pointed
// by the pointer variable *add_great
*add_great = a;
*add_small = b;

8
Subject: PPS Unit – III

else
{
*add_great = b;
*add_small = a;
}
}
int main()
{
int biggest, smallest, x, y;
printf("Enter two numbers: \n");
scanf("%d%d", &x, &y);
// The last two arguments are passed
// by giving addresses of memory locations
compare(x, y, &biggest, &smallest);
printf("\nThe greater number is %d and the smaller number is %d", biggest, smallest);
}
Output:
Enter two Numbers: 30 20
The greater number is 30 and the smaller number is 20
Pointers to Pointers (Double Pointer)
A variable in C that stores the address of another variable is known as a pointer. A pointer can store the
address of another pointer too, in which case it is called "pointer to pointer" (also called "double
pointer"). A "pointer to a pointer" is a form of multiple indirections or a chain of pointers.
Declaration of Pointer to a Pointer
The declaration of a pointer to pointer (double pointer) is similar to the declaration of a pointer, the only
difference is that we need to use an additional asterisk (*) before the pointer variable name.
The syntax to declare a double pointer is:
data-type **pointer-variable-name;
Example: int **p;
float **p1; char **p2;

9
Subject: PPS Unit – III

The above figure shows how a double pointer is dereferenced

//Program to demonstrate the use of pointer to pointer or double pointer


#include <stdio.h>
int main()
{
int a = 100;
int *ptr = &a; // Pointer to integer
int **dptr = &ptr; // Pointer to pointer (double pointer)
printf("Value of 'a' is : %d\n", a);
printf("Value of 'a' using pointer (ptr) is : %d\n", *ptr);
printf("Value of 'a' using double pointer (dptr) is : %d\n", **dptr);
}

Output:
Value of 'a' is: 100
Value of 'a' using pointer (ptr) is: 100
Value of 'a' using double pointer (dptr) is: 100
Compatibility:
It is important to recognize that pointers have a type associated with them. They are not just pointer
types, but rather are pointers to a specific type. Each pointer therefore takes on the attributes of the type
to which it refers in addition to its own attributes.
Pointer Size Compatibility
The size of all pointers is the same. Every pointer variable holds the address of one memory location in
the computer. On the other hand, the size of the variable that the pointer references can be different; it
takes the attributes of the type of the variable it is being referenced.

10
Subject: PPS Unit – III

// program to demonstrate size of pointers.


#include <stdio.h>
int main (void)
{
// Local Declaration of char type
char c;
char* pc;
int sizeofc= sizeof(c);
int sizeofpc= sizeof(pc);
int sizeofStarpc = sizeof(*pc);
// Local Declaration int type
int a;
int* pa;
int sizeofa= sizeof(a);
int sizeofpa= sizeof(pa);
int sizeofStarpa = sizeof(*pa);
// Local Declaration double type
double x;
double* px;
int sizeofx= sizeof(x);
int sizeofpx= sizeof(px);
int sizeofStarpx = sizeof(*px);
// Statements
printf("\nsizeof(c):%d\n", sizeofc);
printf("\nsizeof(pc):%d\n", sizeofpc);
printf("\nsizeof(*pc):%d\n", sizeofStarpc);
printf("\nsizeof(a): %d\n", sizeofa);
printf("\nsizeof(pa):%d\n", sizeofpa);
printf("\nsizeof(*pa):%d\n" , sizeofStarpa);
printf("\nsizeof(x):%d\n", sizeofx);
printf("\nsizeof(px):%d\n", sizeofpx);
printf("\nsizeof(*px):%d\n", sizeofStarpx);
}
11
Subject: PPS Unit – III

Dereference Type Compatibility


The second issue in compatibility is the dereference type. The dereference type is the type of the
variable that the pointer is referencing. With one exception ( discussed later), it is invalid to assign a
pointer of one type to a pointer of another type, even though the values in both cases are memory
addresses and would therefore seem to be fully compatible. Although the addresses may be compatible
because they are drawn from the same set, what is not compatibility is the underlying data type of the
referenced object (variable).
In C, we can‟t use the assignment operator with pointers to different types; if we try to, we get a compile
error. A pointer to a char is only compatible with a pointer to a char; and a pointer to an int is only
compatible with a pointer to an int. We cannot assign a pointer to a char to a pointer to an int.
Example for the dereference type compatibility is as below

Dereference Level Compatibility


Compatibility also includes dereference level compatibility. For example, a pointer to int is not
compatible with a pointer-to-pointer to int. The pointer to int has a reference type of int, while a pointer-
to-pointer to int has a reference type of pointer to int.
In the below figure two pointers are declared at different levels. The pointer “pa” is a pointer to int; the
pointer “ppa” is a pointer-to-pointer to int.

12
Subject: PPS Unit – III

Lvalue:
In C, an expression is either an Lvalue or an Rvalue. As we know, every expression has a value. But the
value in an expression (after evaluation) can be used in two different ways.
1. An Lvalue expression must be used whenever the object is receiving a value; that is, it is being
modified.
2. An Rvalue expression can be used to supply a value for further use; that is, to examine or copy its
value.
L-value refers to memory location which identifies an object. L-value may appear as either left hand or
right hand side of an assignment operator (=). L-value often represents as identifier. Expressions
referring to modifiable locations are called “modifiable L-values“. L-value can be called as “locator
value”, and referred to expressions that locate (designate) objects.
The L-value is one of the following:
 The name of the variable of any type
i.e. an identifier of integral, floating, pointer, structure, or union type.
 A subscript ([ ]) expression that does not evaluate to an array.
 A unary indirection (*) expression that does not refer to an array.
 An L-value expression in parentheses.
 A const object (a non-modifiable L-value).
 The result of indirection through a pointer provided that it isn‟t a function pointer.
 The result of member access through pointer (-> or .)
Example piece of code for L-values
// declare „a‟ as int variable and „p‟ as pointer variable
int a, *p;
p = &a; // ok, assignment of address at l-value
&a = p; // error: &a is an r-value

13
Subject: PPS Unit – III

int x, y;
( x < y ? y : x) = 0; // It‟s valid because the ternary
// expression preserves the "lvalue-ness"
// of both its possible return values
Rvalue:
R-value” refers to data value that is stored at some address in memory. A R-value is an expression, that
can‟t have a value assigned to it, which means R-value can appear on right but not on left hand side of
an assignment operator(=).

R-value simply means, an object that has no identifiable location in memory (i.e. having an address).

Anything that is capable of returning a constant expression or value. Expression like a+b will return
some constant. All expressions that are not Lvalue expressions are Rvalues.

Pointers and Arrays:


When an array is declared, the compiler allocates a base address and sufficient amount of storage to
contain all the elements of the array in contiguous memory location. The base address is the location of
the first element of the array i.e. (index 0). The compiler also defines the array name as a constant
pointer to the first element.
Example: int x[7]={45,98,76,86,90,56,78};
Suppose the base address of x is 1000 and assuming that each integer requires two bytes,
The five elements will be stored as follows:

Elements: x[0] x[1] x[2] x[3] x[4] x[5] x[6]


Values 45 98 76 86 90 56 78

addresses 1000 1002 1004 1006 1008 1010 1012

Base Address

The name „x‟ is defined as a constant pointer to the first element, x[0] and therefore the values of x
is 1000, the location where x[0] is stored, i.e.
x=&x[0]=1000;
If „p‟ is an integer pointer, then the pointer „p‟ points to the array „x‟ by the following assignment:
p=x; is same as p=&x[0];

14
Subject: PPS Unit – III

every value of an array „x‟ can be accessed using p++ to move from one element to another. The
relationship between „p‟ and „x‟ is shown below:
p=&x[0] (=1000)
p+1=&x[1] (=1002)
p+2=&x[2] (=1003)
p+3=&x[3] (=1006)
Note: Address of an element is calculated using its index and the scale factor of the data type.
Example: address of x[3]=base address+(3 * scale factor of int)
=1000 + (3*2) =1006
/*Example program using pointer and Array for 1D array*/
#include<stdio.h>
int main()
{
int i;
int a[5]={1,2,3,4,5};
int *p=&a[0];
for(i=0;i<5;i++)
{
printf(%d\n”,*p);
p++;
}
}
// Example program using pointer and Array for 2D array *
#include<stdio.h>
int main()
{
int a[3][2]={100,200,300,400,500,600},i,j,*ptr;
ptr=&a[0][0];
for(i=0;i<3;i++)
for(j=0;j<2;j++)
{
printf("Element = %d\n",*ptr);
ptr++;
15
Subject: PPS Unit – III

}
}
Pointer Arithmetic
Pointer Arithmetic is the set of valid arithmetic operations that can be performed on pointers. The
pointer variables store the memory address of another variable. It doesn‟t store any value.
Hence, there are only a few operations that are allowed to perform on Pointers in C language. The C
pointer arithmetic operations are slightly different from the ones that we generally use for mathematical
calculations.
The following are the Arithmetic operations that can be performed on pointers.
1. Add an integer value to a pointer.
Example: if “p” is a pointer then p++, p+2 is valid
2. Subtract an integer value from a pointer
Example: if “p” is a pointer then p--, p-2 is valid
3. Compare two pointers if they point to the elements of the same array.
Example: if “p” is a pointer then p>p+2 is valid
4. Subtract one pointer from another pointer if both points to the same array.
Example: if “p”, “p1” are pointers then p - p1 is valid
5. Assign one pointer to another pointer provided both are of the same type.
Example: if “p”, “p1” are pointers then p = p1 is valid
The following are the Arithmetic operations that cannot be performed on pointers:
1. Addition of two pointers
Example: if “p”, “p1” are pointers then p + p1 is invalid operation
2. Subtraction of a pointer from another pointer when they do not point to the same array.
Example: if “p”, “p1” are pointers then p - p1 is invalid operation
3. Multiplication of two pointers
Example: if “p”, “p1” are pointers then p *p1 is invalid operation
5. Division of one pointer by another pointer.
Example: if “p”, “p1” are pointers then p / p1 is invalid operation
Passing an Array to Function
In C, there are various general problems which require passing more than one variable of the same type
to a function. For example, consider a function which sorts the 10 elements in ascending order. Such a
function requires 10 numbers to be passed as the actual parameters from the main function. Here, instead

16
Subject: PPS Unit – III

of declaring 10 different numbers and then passing into the function, we can declare and initialize an
array and pass that into the function. This will resolve all the complexity since the function will now
work for any number of values.
As we know that the array_name contains the address of the first element. Here, we must notice that we
need to pass only the name of the array in the function which is intended to accept an array. The array
defined as the formal parameter will automatically refer to the array specified by the array name defined
as an actual parameter.
The syntax of function prototype/ declaration which receives entire 1D array as argument is:
return-type function-name (data-type array-name[], data-type array-size);
The syntax of function call which receives entire 1D array as argument is:
function-name(array-name, arry-size);
The syntax of function definition which receives entire 1D array as argument is:
return-type function-name(array-name[], array-size)
{
local variable declarations;
statement 1;
statement 2;
--------
--------
return statement; //if any return value
}
The syntax of function prototype/ declaration which receives entire 2D array as argument is:
return-type function-name (data-type array-name[][col-size], data-type row-size , data-type col-size);
The syntax of function call which receives entire 2D array as argument is:
function-name(array-name, row-size, col-size );
The syntax of function definition which receives entire 2D array as argument is:
return-type function-name(data-type array-name[][col-size], data-type row-size , data-type col-size)
{
local variable declarations;
statement 1;
statement 2;
--------
--------
17
Subject: PPS Unit – III

return statement; //if any return value


}
//Example program to pass entire 1D array to function
#include<stdio.h>
int main()
{
int A[100],i,size;
void doStuff(int x[], int);
printf("enter the size of array\n");
scanf("%d",&size);
printf("enter %d elements of array\n",size);
for(i=0;i<size;i++)
scanf("%d",&A[i]);
doStuff(A,size);
}
void doStuff(int x[],int s)
{
int i;
printf("The array elements are\n");
for(i=0;i<s;i++)
printf("%d\t", x[i]);
}
//Example program to pass entire 2D array to function
#include<stdio.h>
int main()
{
int A[10][10],i,j,r,c;
void doStuff(int x[][10], int,int);
printf("enter the row and col size of array\n");
scanf("%d%d",&r,&c);
printf("enter %d elements of array\n",r*c);
for(i=0;i<r;i++)
for(j=0;j<c;j++)
18
Subject: PPS Unit – III

scanf("%d",&A[i][j]);
doStuff(A,r,c);
}
void doStuff(int x[][10],int row,int col)
{
int i,j;
printf("The array elements are\n");
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
printf("%d\t", x[i][j]);
printf("\n");
}
}
Memory Allocation Functions
The process of reserving memory is called allocation. In C memory can be allocated in two different
ways,
 Static Memory Allocation
 Dynamic Memory Allocation

Static Memory
Static Memory is memory that is reserved for variables before the program runs. Allocation of static
memory is also known as Compile Time Memory Allocation. C automatically allocates memory for
every variable when the program is compiled.
 Static memory allocation requires that the declaration and definition of memory should be
specified in the source program.

19
Subject: PPS Unit – III

 If memory is allocated at compile time, it cannot be changed during execution. There will be a
problem of either insufficiency or else wastage of memory.
 The solution is to create memory dynamically i.e. as per the requirement of the user during
execution of the program.
Dynamic Memory
Dynamic Memory is memory that is allocated after the program starts running. Allocation of dynamic
memory can also be referred to as Runtime Memory Allocation.
It uses predefined functions to allocate and release memory for the data while the program is running.
It postpones the data definition, but not data declaration. Unlike static memory allocation, dynamic
memory allocation does not have an identifier, it has only an address that must be used to access it, and
therefore we must use pointers.
“C” Dynamic Memory Allocation
It can be defined as a procedure in which the size of a data structure (like Array) is changed during the
runtime.
Why do we use Dynamic Memory Allocation?
Since C is a structured language, it has some fixed rules for programming. One of them includes
changing the size of an array. An array is a collection of items stored at contiguous memory locations

As it can be seen that the length (size) of the array above is 9. But what if there is a requirement to
change this length (size). For Example,
 If there is a situation where only 5 elements are needed to be entered in this array. In this case,
the remaining 4 indices are just wasting memory in this array. So there is a requirement to lessen
the length (size) of the array from 9 to 5.
 Take another situation. In this, there is an array of 9 elements with all 9 indices filled. But there
is a need to enter 3 more elements in this array. In this case, 3 more indices are required. So, the
length (size) of the array needs to be changed from 9 to 12.

20
Subject: PPS Unit – III

The above two situations cannot be handle by using Static Memory Allocation. Hence to handle such a
situation we use Dynamic Memory Allocation.
There are 4 library functions provided by C defined under <stdlib.h> header file to facilitate Dynamic
Memory Allocation in C programming. They are:
1.malloc()
2.calloc()
3.free()
4.realloc()
1) malloc ( ):
 This function is used for allocating a block of memory in bytes at runtime.
 It returns a void pointer, which points to the base address of allocated memory
 The allocated memory is not initialized, so it will contain garbage values.
 The malloc() function allocates a block of memory of requested size and returns a pointer to the
first byte of the block.
Syntax:
void *malloc (size in bytes);
The type-casting format of malloc function is:
Pointer-varible=(type *) malloc(size) to make portability, the size is computed by using sizeof operator.
Example:
1) int *ptr; ptr = (int * ) malloc (1000);
2) int *ptr; ptr = (int * ) malloc (n * sizeof (int));
Note: if the memory is not free, it returns NULL

21
Subject: PPS Unit – III

//Example program to demonstrate “malloc” function


#include<stdio.h>
#include<stdlib.h>
int main()
{
int *a,n,i;
printf("Enter the number of elements\n");
scanf("%d",&n);
a=malloc(n*(sizeof(int)));
printf("Enter %d elements\n",n);
for(i=0;i<n;i++)
scanf("%d ",a+i);
for(i=0;i<n;i++)
printf("%d ",*(a+i));
free(a);
}
2) Calloc ( ):
 This function is used for allocating continuous blocks of memory at run time.
 This is especially designed for arrays.
 It returns a void pointer which points to the base address of the allocated memory.
 It allocates multiple blocks of memory, all of which are of the same size and returns a pointer to
the first byte of the first block.
 The memory block allocated will be filled with 0‟s.
Syntax:
void *calloc (numbers of elements, size in bytes);
Example:
1) int *ptr; ptr = (int * ) calloc (500,2); Here, 500 blocks of memory each of size 2 bytes will be
allocated continuously. Total memory allocated = 1000 bytes.
2) int *ptr; ptr = (int * ) calloc (n, sizeof (int));

22
Subject: PPS Unit – III

//Example program to demonstrate “calloc” function


#include<stdio.h>
#include<malloc.h>
int main()
{
int *a,n,i;
printf("Enter the number of elements\n");
scanf("%d",&n);
a=calloc(n,2);
printf("Enter %d elements\n",n);
for(i=0;i<n;i++)
scanf("%d ",a+i);
for(i=0;i<n;i++)
printf("%d ",*(a+i));
free(a);
}
3. realloc ( ):
malloc() and calloc() are used to dynamically allocate memory space required to store data. At times, we
may need to alter the size of the memory block allocated by either malloc() or calloc() during runtime
itself. The realloc() does it.
 It is used for reallocating already allocated memory
 It can either reduce (or) extend the allocated memory.
 It returns a void pointer that points to the base address of reallocated memory.

Syntax:
new_pointer = (datatype*) realloc (old_pointer, newsize);
23
Subject: PPS Unit – III

//Example program to demonstrate “realloc” function


#include<stdio.h>
//To use realloc in our program
#include<stdlib.h>
int main()
{
int *ptr,i;
//allocating memory for only 1 integer
ptr = malloc(sizeof(int));
ptr[0] = 1;
//realloc memory size to store 3 integers
ptr = realloc(ptr, 3 * sizeof(int));
ptr[1] = 2;
ptr[2] = 3;
//printing values
for(i = 0; i < 3; i++)
printf("%d\n",ptr[i]);
}
4. free ( ):
 This function frees (or) deallocates previously allocated memory space.
 With dynamic runtime allocation, it is our responsibility to release the space when it is not
required for effective usage of memory.
Syntax:
void *free (pointer);

24
Subject: PPS Unit – III

//Example program to demonstrate “free” function


#include<stdio.h>
#include<stdlib.h>
int main()
{
int *ptr,n,i,sum = 0;
//get number of elements
scanf("%d",&n);
//allocate dynamic memory
ptr = malloc(n * sizeof(int));
//if success
if(ptr != NULL)
{
//get input from the user
for(i = 0; i < n; i++)
scanf("%d", ptr + i);
//add all elements
for(i = 0; i < n; i++)
sum += *(ptr + i);
printf("sum = %d\n",sum); //print the result
free(ptr); //deallocate the memory
//you may get garbage values because memory is deallocated
for(i = 0; i < n; i++)
printf("%d", ptr + i);
}
}

25
Subject: PPS Unit – III

Array of Pointers
A pointer array is a homogeneous collection of indexed pointer variables that are references to a
memory location. It is generally used in Programming when we want to point at multiple memory
locations of a similar data type in our program. We can access the data by dereferencing the pointer
pointing to it.
Syntax:
pointer_type *array_name [array_size];
Here,
pointer_type: Type of data the pointer is pointing to.
array_name: Name of the array of pointers.
array_size: Size of the array of pointers.
Note: It is important to keep in mind the operator precedence and associativity in the array of pointers
declarations of different type as a single change will mean the whole different thing.
For example, enclosing *array_name in the parenthesis will mean that array_name is a pointer to an
array.
// program to demonstrate the use of array of pointers
#include <stdio.h>
int main()
{
// declaring some temp variables
int var1 = 10;
int var2 = 20;
int var3 = 30;
int i;
// array of pointers to integers
int *ptr_arr[3] = { &var1, &var2, &var3 };
// traversing using loop
for ( i = 0; i < 3; i++)
{
printf("Value of var%d: %d\tAddress: %p\n", i + 1, *ptr_arr[i], ptr_arr[i]);
}
}

26
Subject: PPS Unit – III

Application of Array of Pointers


An array of pointers is useful in a wide range of cases. Some of these applications are listed below:
 It is most commonly used to store multiple strings.
 It is also used to implement LinkedHashMap in C and also in the Chaining technique of collision
resolving in Hashing.
 It is used in sorting algorithms like bucket sort.
 It can be used with any pointer type so it is useful when we have separate declarations of
multiple entities and we want to store them in a single place.
Void Pointer
A void pointer in C is a type of pointer that is not associated with any data type. A void pointer can
hold an address of any type and can be type-casted to any type. They are also called general-purpose
or generic pointers.
In C, the function malloc() and calloc() return "void *" or generic pointers.
Syntax to declare a void pointer is:
void *ptr;
// program to demonstrate void pointers
#include <stdio.h>
int main()
{
int a = 10;
char b = 'x';
void *ptr
// void pointer holds address of int a
ptr = &a;
printf("Address of 'a': %d", &a);
printf("\nVoid pointer points to: %d", ptr);
// it now points to char b
ptr = &b;
printf("\nAddress of 'b': %d", &b);

printf("\nVoid pointer points to: %d", ptr);


}

27
Subject: PPS Unit – III

Pointers to Functions
A pointer is a variable that stores the address of another variable. Like a variable, a function has a type
(data type) and address location in memory. So it is possible to declare a pointer variable to a function.
The syntax to declare a pointer to function is:
type (*fptr) ();
This tells the compiler that “fptr” is a pointer to function, which returns type value. The parenthesis
around “*fptr” is necessary.
Note: if we declare type *gprt() will be considered as function returning pointer type.
We can make a function pointer to point to a specific function by simply assigning the name of the
function to the pointer.
For example
int mul(int, int);
int (*p) ();
p=mul;
Now “mul” can be called using the below statement
(*p) (x,y); //function call
// program1 to demonstrate pointer to functions
#include <stdio.h>
// Defining a function
void hello()
{
printf("Hello World");
}
int main()
{
// Declaring a function pointer

void (*ptr)() = &hello;


// Calling function using the function pointer
(*ptr) ();
}

28
Subject: PPS Unit – III

// program2 to demonstrate pointer to functions


#include <stdio.h>
int addition (int a, int b)
{
return a + b;
}
int main(){
int (*ptr)(int, int) = addition;
int x = 10, y = 20;
int z = (*ptr)(x, y);
printf("Addition of x: %d and y: %d = %d", x, y, z);
}

Command line arguments


The arguments which are passed to the main function from command line are called command line
arguments
The syntax of command line arguments is:
int main(int argc, char argv[]) { / ... */ }
or
int main(int argc, char *argv) { / ... */ }
Here,
“argc” (ARGument Count) is an integer variable that stores the number of command-line arguments
passed by the user including the name of the program. So if we pass a value to a program, the value of
“argc” must pass at least two arguments (one for argument and one for program name). The value of
“argc” should be non-negative.
„argv” (ARGument Vector) is an array of character pointers listing all the arguments. If “argc” is greater
than zero, the array elements from argv[0] to argv[argc-1] will contain pointers to strings. argv[0] is the
name of the program , After that till argv[argc-1] every element is command -line arguments.
// C program named mainreturn.c to demonstrate the working of command line argument
#include <stdio.h>
// defining main with arguments
int main(int argc, char* argv[])
{

29
Subject: PPS Unit – III

printf("You have entered %d arguments:\n", argc);


for (int i = 0; i < argc; i++)
{
printf("\n argument %d is %s\n", i, argv[i]);
}
}

STRINGS
Strings Concept
String is a data type that represents a sequence of characters, such as letters, numbers, symbols, and
spaces. Strings are often used in programming to store and manipulate text. (OR)
The string can be defined as the one-dimensional array of characters terminated by a null ('\0'). The
character array or the string is used to manipulate text such as word or sentences. Each character in the
array occupies one byte of memory, and the last character must always be '\0'. The termination character
('\0') is important in a string since it is the only way to identify where the string ends. When we define a
string as char s[10], the character s[10] is implicitly initialized with the null in the memory.
Some of the important things about the strings are:
Enclosed in quotation marks: Strings are enclosed in double quotations.
For example, "liquid" and "What is liquid? It's a template language" are both strings.
Case sensitive: Strings are case sensitive.
Implemented as an array: Strings are often implemented as an array data structure of bytes or words.
Different in different programming languages: How strings are treated can vary between
programming languages. For example, in Java, strings are objects of the String class, while in other
languages they are treated as arrays of characters.
String Declaration Syntax:
char string_name[size];
In the above syntax string_name is any name given to the string variable and size is used to define the
length of the string, i.e. the number of characters strings will store.
There is an extra terminating character which is the Null character („\0‟) used to indicate the termination
of a string that differs from normal arrays.

30
Subject: PPS Unit – III

String Initialization:
We can initialize string in 4 different ways which are as follows:

1. Assigning a String Literal without Size


String literals can be assigned without size. Here, the name of the string “str” acts as a pointer because it
is an array.
char str[] = "helloworld";

2. Assigning a String Literal with a Predefined Size


String literals can be assigned with a predefined size. But we should always account for one extra space
which will be assigned to the null character. If we want to store a string of size n then we should always
declare a string with a size equal to or greater than n+1.

char str[50] = " helloworld ";

3. Assigning Character by Character with Size


We can also assign a string character by character. But we should remember to set the end character as
„\0‟ which is a null character.

char str[10] = { 'h','e','l','l','o','w','o','l','d','\0'};

4. Assigning Character by Character without Size


We can assign character by character without size with the NULL character at the end. The size of the
string is determined by the compiler automatically.

char str[] = { 'h','e','l','l','o','w','o','l','d','\0'};

Note: When a Sequence of characters enclosed in the double quotation marks is encountered by the
compiler, a null character „\0‟ is appended at the end of the string by default.

String Input Output Functions


In C, input refers to providing it with some information or data to be utilized in the program. On the
other hand, output refers to writing the data and information on any printer file and displaying it on the
screen. A standard library is available in the C language for reading any input and generating the output
to be displayed on the console.

31
Subject: PPS Unit – III

There are mainly two types of these functions available in the C language:
Formatted
The formatted functions basically present or accept the available data (input) in a specific format. The
standard library in C contains various functions for the input-output operations. The scanf() and printf()
out of these functions help a programmer format the functions in their desired format. The program can
use these functions for reading any form of data, like a real number, an integer, a character, and many
more.
Unformatted
The unformatted functions are not capable of controlling the format that is involved in writing and
reading the available data. Thus, these functions constitute the most basic forms of output and input. The
supply of input or the display of output isn‟t allowed in the user format – thus, we call these functions
unformatted functions for input and output.
The unformatted input-output functions further have two categories:
The character functions
The string functions
We use the character input functions for reading only a single character from the input device (the
keyboard). On the other hand, we use the character output functions for writing just a single character on
the output source (the screen). Here, the getchar(), getche(), and the getch() refer to the input functions
of unformatted type, while the putchar() and putch() refer to the output functions of unformatted type.
The string output and input. In any programming language, the character array or string refers to the
collection of various characters. Now, various types of input and output functions are present in C
programming that can easily read and write these strings. The puts() and gets() are the most commonly
used ones. Here, the gets() refers to the input function used for reading the string characters while the
puts() refers to the output function used for writing the string characters (in unformatted forms).
// C program to read and print a character using getcha() and putchar()
#include <stdio.h>
int main()
{
int character;
printf("Enter any random character between a-z: ");
character = getchar();

32
Subject: PPS Unit – III

printf("The entered character is : ");


putchar(character);
}
// C program to read and print a character using scanf() and printf()
#include <stdio.h>
int main()
{
char ch;
scanf("%c", &ch);
printf("Output : %c", ch);
}
// C program to read and print string using scanf() and printf()
#include <stdio.h>
#include <string.h>
int main()
{
char str[] = "deccan college";
char name[50];
printf("enter a string\n");
scanf("%s",name);
printf("The entered string is\n");
printf("%s\n", name);
printf("The initialized string is\n");
printf("%s\n", str);
}
// C program to read and print string using gets() and puts()
#include <stdio.h>
#include <string.h>
int main()
{
char name[50];
printf("enter a string\n");
gets(name);
33
Subject: PPS Unit – III

printf("The entered string is\n");


puts(name);
}
Strings can be printed using normal “printf” statements just like we print any other variable. Unlike
arrays, we do not need to print a string, character by character.
Note: The C language does not provide an inbuilt data type for strings but it has an access specifier
“%s” which can be used to print and read strings directly.

Arrays of Strings
Definition:
An array of strings is a two-dimensional array of character-type arrays where each character array
(string) is null-terminated.
Declaration of an Array of Strings
To declare an array of strings, we need to declare a two-dimensional array of character types, where the
first subscript is the total number of strings and the second subscript is the maximum size of each string.
Syntax of array of string declaration is:
char strings [no_of_strings] [max_size_of_each_string];
Here:
no_of_strings: specifies maximum number of strings that can be stored.
max_size_of_each_string: specifies maximum number of characters each string contains.

Example: char langs [10][15];


char stdname[60][20];
char empname[100][50];
Initialization of an Array of Strings
To initialize an array of strings, we need to provide the multiple strings inside the double quotes
separated by the commas.
Syntax of array of strings initialization is:
char strings [no_of_strings] [max_size_of_each_string]= {“ list of strings separated by commas”};
Example: char lang[10][15] = {
"PYTHON", "JAVASCRIPT", "PHP",
"NODE JS", "HTML", "KOTLIN", "C++",
"REACT JS", "RUST", "VBSCRIPT" };

34
Subject: PPS Unit – III

//C program to demonstrate array of strings


#include <stdio.h>
int main ()
{
char langs [10][15];
int n, i;
printf("how many strings you wants to store\n");
scanf("%d",&n);
printf("enter %d strings\n", n);
for (i=0;i<n;i++)
scanf("%s", langs[i]);
printf("how many strings you wants to sore\n");
for (i = 0; i < n; i++)
printf("%s\n", langs[i]);
}
An Array of Strings with Pointers
To use the memory more efficiently, we can use the pointers. Instead of a 2D char array, we declare a
1D array of "char *” pointer type.
The syntax to declare and initialize an array of strings with pointers is:

char *langs[no. of strings]; // declaration of an array of strings with pointers

Example:
char *langs[10];
char *langs[no. of strings]={“list of strings separated by commas”};

char *langs[10] = {
"PYTHON", "JAVASCRIPT", "PHP",
"NODE JS", "HTML", "KOTLIN", "C++",
"REACT JS", "RUST", "VBSCRIPT"
}; // initialization of an array of strings with pointers

35
Subject: PPS Unit – III

//C program to demonstrate array of strings with pointers


#include <stdio.h>
int main()
{
int i;
char *langs[10] = {
"PYTHON", "JAVASCRIPT", "PHP",
"NODE JS", "HTML", "KOTLIN", "C++",
"REACT JS", "RUST", "VBSCRIPT"
};
for (i = 0; i < 10; i++)
printf("%s\n", langs[i]);
}
STRING MANIPULATION FUNCIOTNS (OR) THE STRING HANDLING LIBRARY:
The string handling library provides many useful functions for manipulating strings. Following are the
most commonly used string – handling functions. These functions are defined in “string.h” header file.
String Length: strlen():

This function counts and returns the number of characters in a string.

The function prototype of this function is


int strlen(const char *s)
It returns length of the string therefore the return type of the function is “int” and it takes string constant
as argument.
Example: a) len=strlen(“INDIA”);

b) char str[10]=”INDIA”

int len;

len=strlen(str);

String Compare: strcmp():


This is a function which compares two strings to find out whether they are similar or different. The two
strings are compared character by character until there is a mismatch or end of one of the strings is
reached, whichever occurs first. If the two strings are identical, strcmp() returns a value zero. If they‟re

36
Subject: PPS Unit – III

not, it returns the numeric difference between the ASCII values of the first non-matching pairs of
characters. The prototype of this function is
int strcmp(const char *s1,const char *s2);

String Copy: strcpy():


This function copies the contents of one string into another. The base of the source and the target string
should be supplied to this function. The prototype of this function is
char *strcpy(char *target, const char *source);
It takes the general form
strcpy(str1,str2);
The above function assigns the contents of “str2” to “str1”. “Str2” may be a character array variable or a
string constant.
For example
char city1[20],city[20];

char city1[20]=”CULCUTTA”;

strcpy(city,”DELHI”);
By the above statement the string constant “DELHI” will be copied in a string called “city”.
strcpy(city2,city1);
By the above statement the string “city1” will be copied in a string called “city2”.
NOTE: The size of the target string should be greater or equal to the size of the source string.

String Concatenate: strcat():


This function concatenates (joins) the source string at the end of the target string.
The function prototype is
char *strcat(char *target, const char *source);
It takes the following form
strcat(target, source);
Here source string is appended to target string. It does so by removing the null character at the end of the
target string and placing source string from there. The source string remains unchanged.
For example,

char lname[20]=”John”;

char fname[20]=”Hello”;
strcat(fname, lname);
37
Subject: PPS Unit – III

On concatenating will result into target string (i.e. fname) “HelloJohn”. That is source string is added at
the end of target string. So target string containing the combined string.
C allows the nesting of “strcat()” function
Example: strcat(strcat(str1,str2),str3);

Is allowed and concatenates all the three strings together. The result is stored in “str1”.
NOTE: The size of the target string should be large enough to join the source string.

String Reverse strrev():


This function is used to reverse the given string. Reversed string will be placed in the same array.
The prototype of this function is
char *strrev(char *str-name);

the above functions reverse the given string i.e. str-mame

Example: strrev(str);

Program to demonstrate string manipulation library functions of C

#include <stdio.h>
#include<string.h>
int main ( )
{
char s1 [100], s2 [100], a [100], b [100];
int n;
printf ("Enter the first string: ");
gets (s1);
printf ("Enter the second string: ");
gets (s2);
n=strlen(s1);
printf("\nLenght of first string is: %d\n",n);
n=strlen(s2);
printf("Lenght of second string is: %d\n",n);
if(strcmp (s1, s2)==0)
printf("\nStrings are equal\n");
else
printf("\nStrings are not equal\n");
38
Subject: PPS Unit – III

strcat (s1, s2);


printf ("\nThe concatinated string is: %s\n",s1);
printf("\nReverse of second string is: %s\n",strrev(s2));
printf("\nEnter a string that is to be copied:");
gets (a);
printf("\nThe Entered string to be copied is %s:\n\n",a);
strcpy (b, a);
printf ("The string after being copied is: %s\n",b);
}

39

You might also like