Sunteți pe pagina 1din 22

ANURAG GROUP OF INSTITUTIONS

(CVSR COLLEGE OF ENGINEERING)

UNIT-III (POINTERS)
POINTERS :
One of the powerful features of C is ability to access the memory variables by
their memory address. This can be done by using Pointers. The real power of C lies in
the proper use of Pointers.
A pointer is a variable that can store an address of a variable (i.e., 112300).We say
that a pointer points to a variable that is stored at that address. A pointer itself usually
occupies 4 bytes of memory (then it can address cells from 0 to 232-1).

Advantages of Pointers :

A pointer enables us to access a variable that is defined out side the function.
Pointers are more efficient in handling the data tables.
Pointers reduce the length and complexity of a program.
They increase the execution speed.

Definition :
A variable that holds a physical memory address is called a pointer variable or
Pointer.
Declaration :
Datatype * Variable-name;

Eg:- int *ad; /* pointer to int */


char *s; /* pointer to char */
float *fp; /* pointer to float */
char **s; /* pointer to variable that is a pointer to char */

A pointer is a variable that contains an address which is a location of another variable


in memory.

int i,*p;
Consider the Statement
p=&i;
Here ‘&’ is called address of a variable.
‘p’ contains the address of a variable i.
The operator & returns the memory address of variable on which it is operated,
this is called Referencing.
The * operator is called an indirection operator or dereferencing operator which
is used to display the contents of the Pointer Variable.

Consider the following Statements :

int *p,x;
x =5;
p= &x;

COMPUTER PROGRAMMING-II Page 1


ANURAG GROUP OF INSTITUTIONS
(CVSR COLLEGE OF ENGINEERING)
Assume that x is stored at the memory address 2000. Then the output for the
following printf statements is :

Printf(“The Value of x is %d”,x);


Printf(“The Address of x is %u”,&x);
Printf(“The Address of x is %u”,p);
Printf(“The Value of x is %d”,*p);
Printf(“The Value of x is %d”,*(&x));

Output
The Value of x is 5
The Address of x is 2000
The Address of x is 2000
The Value of x is 5
The Value of x is 5

USAGE OF POINTERS:

Pointers are an extremely powerful programming tool. They can make some things much
easier, help improve your program's efficiency, and even allow you to handle unlimited
amounts of data.
Pointers are used (in the C language) in three different ways:
1. To create dynamic data structures.
2. To pass and handle variable parameters passed to functions.
3. To access information stored in arrays. (Especially if you work with links).
4. Pointers are also used by experienced programmers to make the code more efficient
and thus faster.

POINTERS TO POINTERS :
So far, all pointers have been pointing directely to data. It is possible and with
advanced data structures often necessary to use pointers to that point to other pointers.
For example,we can have a pointer pointing to a pointer to an integer.This two level
indirection is seen as below:
//Local declarations
int a;
int* p;
int **q;

q p a
Ex: 234560 287650 58

397870 234560 287650

pointer to pointer to integer pointer to integer integer variable

//statements

COMPUTER PROGRAMMING-II Page 2


ANURAG GROUP OF INSTITUTIONS
(CVSR COLLEGE OF ENGINEERING)
a=58;
p=&a;
q=&p;
printf(“%3d”,a);
printf(“%3d”,*p);
printf(“%3d”,**q);
There is no limit as to how many level of indirection we can use but practically we
seldom use more than two. Each level of pointer indirection requires a separate indirection
operator when it is dereferenced.

In the above figure to refer to ‘a’ using the pointer ‘p’, we have to dereference it as
shown below.
*p
To refer to the variable ‘a’ using the pointer ‘q’ ,we have to dereference it twice to get to the
integer ‘a’ because there are two levels of indirection(pointers) involved. If we dereference it
only once we are referring ‘p’ which is a pointer to an integer .Another way to say this is that
‘q’ is a pointer to a pointer to an integer.The doule dereference is shown below:
**q
In above example all the three references in the printf statement refer to the variable ‘a’.
The first printf statement prints the value of the variable ‘a’ directly, second uses the pointer
‘p’, third uses the pointer ‘q’. The result is the value 58 printed 3 times as below

58 58 58

Pointer Expressions:
We can perform arithmetic operations on pointer variable just as you can a numeric value. As
we know that, a pointer in C is a variable which is used to store the memory address which is
a numeric value. The arithmetic operations on pointer variable effects the memory address
pointed by pointer.

Valid Pointer Arithmetic Operations


1. Adding a number to pointer.
2. Subtracting a number form a pointer.
3. Incrementing a pointer.
4. Decrementing a pointer.
5. Subtracting two pointers.
6. Comparison on two pointers.
Invalid Pointer Arithmetic Operations
1. Addition of two pointers.
2. Division of two pointers.
3. Multiplication of two pointers.
Incrementing a Pointer:

Let ptr be an integer pointer which points to the memory location 5000 and size of an integer
variable is 32-bit(4 bytes). Now, when we increment pointer ptr
ptr++;

COMPUTER PROGRAMMING-II Page 3


ANURAG GROUP OF INSTITUTIONS
(CVSR COLLEGE OF ENGINEERING)
it will point to memory location 5004 because it will jump to the next integer location which
is 4 bytes next to the current location. Incrementing a pointer is not same as incrementing
an integer value. On incrementing, a pointer will point to the memory location after skipping
N bytes, where N is the size of the data type(in this case it is 4).
ptr++ is equivalent to ptr + (sizeof(pointer_data_type)).
"Incrementing a pointer increases its value by the number of bytes of its data type"
A character(1 bytes) pointer on increment jumps 1 bytes.
An integer(4 bytes) pointer on increment jumps 4 bytes.

This is a very important feature of pointer arithmetic operations which we will use in
array traversal using pointers.

Decrementing a Pointer:
Similarly, Decrementing a pointer will decrease its value by the number of bytes of its data
type. Hence, after
ptr--;
ptr will point to 4996.
ptr--; is equivalent to ptr - (sizeof(pointer_data_type)).

Adding Numbers to Pointers


Adding a number N to a pointer leads the pointer to a new location after skipping N times
size of data type.
ptr + N = ptr + (N * sizeof(pointer_data_ype))
For example, Let ptr be a 4-byte integer pointer, initially pointing to location 5000.
Then ptr + 5 = 5000 + 4*5 = 5020. Pointer ptr will now point at memory address 5020.

Subtracting Numbers from Pointers


Subtracting a number N from a pointers is similar to adding a number except in Subtraction
the new location will be before current location by N times size of data type.
ptr - N = ptr - (N * sizeof(pointer_data_ype))
For example, Let ptr be a 6-byte double pointer, initially pointing to location 5000.
Then ptr - 3 = 5000 - 6*3 = 4982. Pointer ptr will now point at memory address 4982.

Subtracting Pointers
The difference between two pointer returns indicates “How apart the two Pointers are. It
gives the total number of elements between two pointers.
For example, Let size of integer is 4 bytes. If an integer pointer 'ptr1' points at memory
location 10000 and integer pointer 'ptr' points at memory location 10008, the result of ptr2 -
ptr1 is 2.

C program to show pointer arithmetic


#include<stdio.h>
#include<conio.h>

void main() {
int int_var = 10, *int_ptr;
char char_var = 'A', *char_ptr;
float float_val = 4.65, *float_ptr;

COMPUTER PROGRAMMING-II Page 4


ANURAG GROUP OF INSTITUTIONS
(CVSR COLLEGE OF ENGINEERING)

/* Initialize pointers */
int_ptr = &int_var;
char_ptr = &char_var;
float_ptr = &float_val;

printf("Address of int_var = %u\n", int_ptr);


printf("Address of char_var = %u\n", char_ptr);
printf("Address of float_var = %u\n\n", float_ptr);

/* Incrementing pointers */
int_ptr++;
char_ptr++;
float_ptr++;
printf("After increment address in int_ptr = %u\n", int_ptr);
printf("After increment address in char_ptr = %u\n", char_ptr);
printf("After increment address in float_ptr = %u\n\n", float_ptr);

/* Adding 2 to pointers */
int_ptr = int_ptr + 2;
char_ptr = char_ptr + 2;
float_ptr = float_ptr + 2;

printf("After addition address in int_ptr = %u\n", int_ptr);


printf("After addition address in char_ptr = %u\n", char_ptr);
printf("After addition address in float_ptr = %u\n\n", float_ptr);

getch();
return 0;
}

Output
Address of int_var = 2293300
Address of char_var = 2293299
Address of float_var = 2293292

After increment address in int_ptr = 2293304


After increment address in char_ptr = 2293300
After increment address in float_ptr = 2293296

After addition address in int_ptr = 2293312


After addition address in char_ptr = 2293302
After addition address in float_ptr = 2293304

COMPUTER PROGRAMMING-II Page 5


ANURAG GROUP OF INSTITUTIONS
(CVSR COLLEGE OF ENGINEERING)
POINTERS AND ARRAYS :
When an array is declared, elements of array are stored in contiguous locations.
The address of the first element of an array is called its base address.
The interaction of pointers and arrays can be confusing but here are two fundamental
statements about it:
A variable declared as an array of some type acts as a pointer to that type. When used
by itself, it points to the first element of the array.
A pointer can be indexed like an array name.

Consider the array

2000 2002 2004 2006 2008

a[0] a[1] a[2] a[3] a[4]

The name of the array is called its base address.

i.e., a and & a[0] are equal.

Now both a and a[0] points to location 2000. If we declare p as an integer pointer, then
we can make the pointer P to point to the array a by following assignment

P = a;

We can access every value of array a by moving P from one element to another.
i.e., P points to 0th element
P+1 points to 1st element
P+2 points to 2nd element
P+3 points to 3rd element
P +4 points to 4th element

Reading and Printing an array using Pointers :


Void main()
{
int *a,i;
printf(“Enter five elements:”);
for (i=0;i<5;i++)
scanf(“%d”,a+i);
printf(“The array elements are:”);
for (i=o;i<5;i++)
printf(“%d”, *(a+i));
}

In one dimensional array, a[i] element is referred by

COMPUTER PROGRAMMING-II Page 6


ANURAG GROUP OF INSTITUTIONS
(CVSR COLLEGE OF ENGINEERING)
(a+i) is the address of ith element.
* (a+i) is the value at the ith element.

In two-dimensional array, a[i][j] element is represented as


*(*(a+i)+j).

Example: Program to find the sum of six numbers with arrays and pointers
#include <stdio.h>
int main()
{
int i, a[6],sum = 0;
printf("Enter 6 numbers:\n");
for(i = 0; i < 6; ++i)
{
// (a + i) is equivalent to &a[i]
scanf("%d",(a + i));
// *(a + i) is equivalent to a[i]
sum += *(a + i);
}
printf("Sum = %d", sum);
return 0;
}
Output
Enter 6 numbers:
2
3
4
5
3
4
Sum = 21

Arrays of Pointers:
There may be a situation when we want to maintain an array, which can store pointers to an
int or char or any other data type available. Following is the declaration of an array of
pointers to an integer:

Syntax to declare pointer to an array is

datatype (*pointer_variable)[size];

For example

int (*ptr)[10]; ,Here ptr is a pointer that can point to an array of 10 integers, where we can
initialize ptr with the base address of the array then by incre menting the value of ptr we can
access different elements of array a[].

COMPUTER PROGRAMMING-II Page 7


ANURAG GROUP OF INSTITUTIONS
(CVSR COLLEGE OF ENGINEERING)
#include <stdio.h>
const int MAX = 3;
int main ()
{
int var[] = {10, 100, 200};
int i, *ptr[MAX];
for ( i = 0; i < MAX; i++)
{
ptr[i] = &var[i]; /* assign the address of integer. */
}
for ( i = 0; i < MAX; i++)
{
printf("Value of var[%d] = %d\n", i, *ptr[i] );
}
return 0;
}
Output:
Value of var[0] = 10
Value of var[1] = 100
Value of var[2] = 200
ARRAYS OF STRINGS AS POINTER ARRAYS
The declaration of an array of character pointers is an extremely useful extension to single
string pointer declarations.
For example:
char *names[2];
Creates a two element array of character pointers (i.e. each element is a pointer to a
character). As individual pointers each can be assigned to point to a string using a normal
assignment statement:
names[0] = "Frans";
names[1] = "Coenen";

Alternatively we can initialise the names array as shown in the following programs:
#include< stdio.h>
void main(void)
{
char *names[2] = {"Frans", "Coenen"};
/* Output */
printf("names = %s, %s\n",names[0],names[1]);
/* New assignments */
names[0] = "Ray";
names[1] = "Paton";
/* Output */
printf("names = %s, %s\n",names[0],names[1]);
}
In the above the declaration of names both creates an array of pointers and initilises
the pointers with appropriate addresses. Once addresses have been assigned to the pointers,
each pointer can be used to access its corresponding string. The output from the above is as
follows:

COMPUTER PROGRAMMING-II Page 8


ANURAG GROUP OF INSTITUTIONS
(CVSR COLLEGE OF ENGINEERING)
names = Frans, Coenen
names = Ray, Paton

You can also use an array of pointers to character to store a list of strings as

#include <stdio.h>
const int MAX = 4;
int main ()
{
char *names[] = {"Zara Ali", "Hina Ali", "Nuha Ali", "Sara Ali"};
int i = 0;
for ( i = 0; i < MAX; i++)
{
printf("Value of names[%d] = %s\n", i, names[i] );
}
return 0;
}
When the above code is compiled and executed, it produces the following
Value of names[0] = Zara Ali
Value of names[1] = Hina Ali
Value of names[2] = Nuha Ali
Value of names[3] = Sara Ali

POINTERS AND FUNCTIONS :

Parameter passing mechanism in ‘C’ is of two types.


1.Call by Value
2.Call by Reference.
The process of passing the actual value of variables is known as Call by Value. The process
of calling a function using pointers to pass the addresses of variables is known as Call by
Reference. The function which is called by reference can change the value of the variable
used in the call.

Example of Call by Value:

#include <stdio.h>
void swap(int,int);
main()
{
int a,b;
printf(“Enter the Values of a and b:”);
scanf(“%d%d”,&a,&b);
printf(“Before Swapping \n”);
printf(“a = %d \t b = %d”, a,b);
swap(a,b);
printf(“After Swapping \n”);
printf(“a = %d \t b = %d”, a,b);

COMPUTER PROGRAMMING-II Page 9


ANURAG GROUP OF INSTITUTIONS
(CVSR COLLEGE OF ENGINEERING)
}
void swap(int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
}

Example of Call by Reference:

#include<stdio.h>
main()
{
int a=10,b=20;
swap (&a, &b);
printf(“After Swapping \n”);
printf(“a = %d \t b = %d”, a,b);
}
void swap(int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}

NULL Pointers:

It is always a good practice to assign a NULL value to a pointer variable 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

COMPUTER PROGRAMMING-II Page 10


ANURAG GROUP OF INSTITUTIONS
(CVSR COLLEGE OF ENGINEERING)
VOID POINTERS:
A void pointer is a pointer that has no associated data type with it. A void pointer can
hold address of any type and can be type casted to any type.

1. In C General Purpose Pointer is called as void Pointer.


2. It does not have any data type associated with it
3. It can store address of any type of variable
4. A void pointer is a C convention for a raw address.
5. The compiler has no idea what type of object a void Pointer really points to ?

Declaration :

Void * pointer_name;

Ex:- void *ptr; // Now ptr is a general purpose pointer variable

When a pointer variable is declared using keyword void – it becomes a general purpose
pointer variable. Address of any variable of any data type (char, int, float etc.)can be assigned
to a void pointer variable.

Dereferencing a void pointer

We have seen about dereferencing a pointer variable in our article – Introduction to pointers
in C. We use the indirection operator * to serve the purpose. But in the case of a void pointer
we need to typecast the pointer variable to dereference it. This is because a void pointer has
no data type associated with it. There is no way the compiler can know (or guess?) what type
of data is pointed to by the void pointer. So to take the data pointed to by a void pointer we
typecast it with the correct type of the data holded inside the void pointers location.

Example program:-
#include
void main()
{
int a=10;
float b=35.75;
void *ptr; // Declaring a void pointer
ptr=&a; // Assigning address of integer to void pointer.
printf("The value of integer variable is= %d",*( (int*) ptr) );// (int*)ptr - is used for type
casting. Where as *((int*)ptr) dereferences the typecasted void pointer variable.
ptr=&b; // Assigning address of float to void pointer.
printf("The value of float variable is= %f",*( (float*) ptr) ); );// (float*)ptr - is used for type
casting. Where as *((float*)ptr) dereferences the typecasted void pointer variable.
}

The output:-
The value of integer variable is= 10
The value of float variable is= 37.75

COMPUTER PROGRAMMING-II Page 11


ANURAG GROUP OF INSTITUTIONS
(CVSR COLLEGE OF ENGINEERING)
POINTERS TO FUNCTIONS:
What is a Function Pointer?
Function Pointers are pointers, i.e. variables, which point to an address of a function. The
running programs get a certain space in the main memory. Both, the executable compiled
program code and the used variables, are put inside this memory. Thus a function in the
program code is also an address. It is only important how the compiler and processor interpret
the memory the function pointer points to. A function can take many types of arguments
including the address of another function. C provides an interesting way to achieve this by
allowing the programmer to decide the algorithm at runtime.

Functions as pointers
• Function code is stored in memory
• Start of the function code or the address of a function is a “function pointer”
• Function pointer is “different” from other pointers since you do not allocate or deallocate
memory with them
• Function pointers can be passed as arguments to other functions or return from functions
Why use function pointers?
• Efficiency
• Elegance
• Runtime binding

Defining a Function Pointer


Functions like variables, can be associated with an address in the memory. We call this a
function pointer. A specific function pointer variable can be defined as follows.
<function return type>(*<Pointer_name>)(function argument list)
For example –
double (*p2f)(double, char)
Here double is a return type of function, p2f is pointer name & (double, char) is an argument
list for the function. Which means the first argument for this function should be double and
the second one would be of char type.

Example:
int (*fn)(int,int) ;
Here we define a function pointer fn, that can be initialized to any function that takes two
integer arguments and return an integer. Here is an example of such a function
int sum(int x, int y)
{
return (x+y);
}
Now to initialize fn to the address of the sum, we can do the following.
fn = &sum /* make fn points to the address of sum */
or simply
fn = sum; /* just ignore the & . Function names are just like array names they are
pointers to the structure they are referring to */
So we use the sum function in two ways.
int x = sum(10,12); /* direct call to the function */
or int x = (*fn)(12,10); /* call to the function through a pointer */

COMPUTER PROGRAMMING-II Page 12


ANURAG GROUP OF INSTITUTIONS
(CVSR COLLEGE OF ENGINEERING)

Lets understand this with the help of an example –

#include<stdio.h>
int sum (int num1, int num2)
{
return sum1+sum2;
}
int main()
{
int (*f2p) (int, int);
f2p = sum;
int op1 = f2p (10, 13);
int op2 = sum (10, 13);

printf("Output 1 – for function call via Pointer: %d",op1);


printf("Output2 – for direct function call: %d", op2);

return 0;
}
Output:

Output 1 – for function call via Pointer: 23


Output2 – for direct function call: 23

Pointers to structure :
Structures can be created and accessed using pointers. A pointer variable of a structure can be
created as below:
struct name
{
member1;
member2;
--------
};

int main()
{
struct name *ptr;
}

Pointer which stores address of structure is called as “Pointer to Structure“.


Explanation :
1. *ptr is pointer to structure to store address of structure.
2. and (*). both represents the same.
3. These operators are used to access data member of structure by using structure’s
pointer.

COMPUTER PROGRAMMING-II Page 13


ANURAG GROUP OF INSTITUTIONS
(CVSR COLLEGE OF ENGINEERING)
Example:

To access structure members using pointers as ptrimg and ptrreal.

EXAMPLE PROGRAM FOR C STRUCTURE USING POINTER:

In this program, “record1” is normal structure variable and “ptr” is pointer structure variable.
As you know, Dot(.) operator is used to access the data using normal structure variable and
arrow() is used to access data using pointer variable.

#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[30];
float percentage;
};

void main()
{
int i;
struct student record1 = {1, "Raju", 90.5};
struct student *ptr;
ptr = &record1;
printf("Records of STUDENT1: \n");
printf(" Id is: %d \n", ptrid);
printf(" Name is: %s \n", ptrname);
printf(" Percentage is: %f \n\n", ptrpercentage);
}
Output:
Records of STUDENT1:
Id is: 1
Name is: Raju
Percentage is: 90.500000

PASSING STRUCTURE TO FUNCTION IN C:


It can be done in below 3 ways.
1. Passing structure to a function by value
2. Passing structure to a function by address(reference)
3. No need to pass a structure – Declare structure variable as global

COMPUTER PROGRAMMING-II Page 14


ANURAG GROUP OF INSTITUTIONS
(CVSR COLLEGE OF ENGINEERING)

EXAMPLE PROGRAM – PASSING STRUCTURE TO FUNCTION IN C BY


VALUE:
In this program, the whole structure is passed to another function by value. It means the
whole structure is passed to another function with all members and their values. So, this
structure can be accessed from called function.
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[20];
float percentage;
};

void func(struct student record);

int main()
{
struct student record;

record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;

func(record);
return 0;
}

void func(struct student record)


{
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
}

OUTPUT:
Id is: 1
Name is: Raju
Percentage is: 86.500000

EXAMPLE PROGRAM – PASSING STRUCTURE TO FUNCTION IN C BY


ADDRESS:
In this program, the whole structure is passed to another function by address. It means only
the address of the structure is passed to another function. The whole structure is not passed to
another function with all members and their values. So, this structure can be accessed from
called function by its address.

COMPUTER PROGRAMMING-II Page 15


ANURAG GROUP OF INSTITUTIONS
(CVSR COLLEGE OF ENGINEERING)
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[20];
float percentage;
};
void func(struct student *record);

int main()
{
struct student record;
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
func(&record);
return 0;
}

void func(struct student *record)


{
printf(" Id is: %d \n", record->id);
printf(" Name is: %s \n", record->name);
printf(" Percentage is: %f \n", record->percentage);
}
Output:
Id is: 1
Name is: Raju
Percentage is: 86.500000

EXAMPLE PROGRAM TO DECLARE A STRUCTURE VARIABLE AS GLOBAL


IN C:
Structure variables also can be declared as global variables as we declare other variables in C.
So, When a structure variable is declared as global, then it is visible to all the functions in a
program. In this scenario, we don’t need to pass the structure to any function separately.
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[20];
float percentage;
};
struct student record; // Global declaration of structure

void structure_demo();

COMPUTER PROGRAMMING-II Page 16


ANURAG GROUP OF INSTITUTIONS
(CVSR COLLEGE OF ENGINEERING)
int main()
{
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
structure_demo();
return 0;
}

void structure_demo()
{
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
}
Output:
Id is: 1
Name is: Raju
Percentage is: 86.500000

Self -Referential Structures:


A self referential data structure is essentially a structure definition which includes at least one
member that is a pointer to the structure of its own kind. A chain of such structures can thus
be expressed as follows.

struct name
{
member 1;
member 2;
...
struct name *pointer;
};
Example:
struct node
{
int info;
struct node *link;
};

The above illustrated structure prototype describes one node that comprises of two
logical segments. One of them stores data/information and the other one is a pointer
indicating where the link component can be found. .Several such inter-connected nodes create
a chain of structures.
The following figure depicts the composition of such a node. The figure is a
simplified illustration of nodes that collectively form a chain of structures or linked list.

COMPUTER PROGRAMMING-II Page 17


ANURAG GROUP OF INSTITUTIONS
(CVSR COLLEGE OF ENGINEERING)

Such self-referential structures are very useful in applications that involve linked data
structures, such as lists and trees. Unlike a static data structure such as array where the
number of elements that can be inserted in the array is limited by the size of the array, a self-
referential structure can dynamically be expanded or contracted. Operations like insertion or
deletion of nodes in a self- referential structure involve simple and straight forward alteration
of pointers.

Dynamic Memory Allocation:


 It is a process of allocating or de-allocating the memory at run time it is called as
dynamically memory allocation.
 When we are working with array or string static memory allocation will be take place
that is compile time memory management.
 When we ate allocating the memory at compile we cannot extend the memory at run
time, if it is not sufficient.
 By using compile time memory management we cannot utilize the memory properly
 In implementation when we need to utilize the memory more efficiently then go for
dynamic memory allocation.
 By using Dynamic Memory Allocation functions we can create required amount of memory.
 Dynamic memory allocation related all predefined functions are declared in following
header files.
 <alloc.h>
 <malloc.h>
 <mem.h>
 <stdlib.h>

DIFFERENCE BETWEEN STATIC MEMORY ALLOCATION AND DYNAMIC


MEMORY ALLOCATION IN C:
Static memory allocation Dynamic memory allocation

In static memory allocation, memory is


allocated while writing the C program. In dynamic memory allocation,
Actually, user requested memory will be memory is allocated while executing
allocated at compile time. the program. That means at run time.

Memory size can’t be modified while Memory size can be modified while
execution. execution.
Example: array Example: Linked list

COMPUTER PROGRAMMING-II Page 18


ANURAG GROUP OF INSTITUTIONS
(CVSR COLLEGE OF ENGINEERING)
Dynamic memory allocation related functions:

1.Malloc()
 By using malloc() we can create the memory dynamically at initial stage.
 Malloc() required one argument of type size type that is data type size malloc() will
creates the memory in bytes format.
 Malloc() through created memory initial value is garbage.

Syntax:
Void *p=(data type *)malloc(n * sizeof(data type));

Note: Dynamic memory allocation related function can be applied for any data type that's
why dynamic memory allocation related functions return void*.
When we are working with dynamic memory allocation type specification will be available at
the time of execution that's why we required to use type casting process.
Example:
int *ptr;
ptr=(int*)malloc(sizeof (int)); //2 byte

char*cptr;
cptr=(char*)malloc(sizeof(char)); //1 byte

/*C program to read a one dimensional array, print sum of all elements along with inputted
array elements using Malloc Memory Allocation.*/

#include <stdio.h>
#include <stdlib.h>
void main()
{
int *arr;
int n,i;
int sum=0;
printf("Enter total number of elements: ");
scanf("%d",&n);
arr=(int*)malloc(n*sizeof(int)); /*allocate memory for limit elements dynamically*/
if(arr==NULL)
{
printf("Insufficient Memory, Exiting... \n");
return 0;
}
printf("Enter %d elements:\n",n);
for(i=0; i<n; i++)
{
printf("Enter element %3d: ",i+1);
scanf("%d",(arr+i));
sum=sum + *(arr+i); /*calculate sum*/

COMPUTER PROGRAMMING-II Page 19


ANURAG GROUP OF INSTITUTIONS
(CVSR COLLEGE OF ENGINEERING)
}

printf("Array elements are:");


for(i=0; i<n; i++)
printf("%3d ",*(arr+i));
printf("\nSum of all elements: %d\n",sum);
}
Output:
Enter total number of elements: 5
Enter 5 elements:
Enter element 1: 11
Enter element 2: 22
Enter element 3: 33
Enter element 4: 44
Enter element 5: 55
Array elements are: 11 22 33 44 55
Sum of all elements: 165

2.Calloc()
 calloc() required 2 arguments of type count, size-type.
 Count will provide number of elements; size-type is data type size.
 calloc() will creates the memory in blocks format.
 Initial value of the memory is zero.

Syntax:
Void *p=(data type *)calloc(n,sizeof(data type));
Int *arr;
arr=(int*)calloc(10, sizeof(int)); // 20 byte
char *str;
str=(char*)calloc(50, siceof(char)); // 50 byte

/*C program to read a one dimensional array, print sum of all elements along with inputted
array elements using Calloc Memory Allocation.*/
#include <stdio.h>
#include <stdlib.h>
void main()
{
int *arr;
int n,i;
int sum=0;
printf("Enter total number of elements: ");
scanf("%d",&n);
arr=(int*)calloc(n,sizeof(int)); /*allocate memory for limit elements dynamically*/
if(arr==NULL)
{
printf("Insufficient Memory, Exiting... \n");
return 0; }

COMPUTER PROGRAMMING-II Page 20


ANURAG GROUP OF INSTITUTIONS
(CVSR COLLEGE OF ENGINEERING)

printf("Enter %d elements:\n",n);
for(i=0; i<n; i++)
{
printf("Enter element %3d: ",i+1);
scanf("%d",(arr+i));
sum=sum + *(arr+i); /*calculate sum*/

printf("Array elements are:");


for(i=0; i<n; i++)
printf("%3d ",*(arr+i));
printf("\nSum of all elements: %d\n",sum);
}
Output:
Enter total number of elements: 5
Enter 5 elements:
Enter element 1: 11
Enter element 2: 22
Enter element 3: 33
Enter element 4: 44
Enter element 5: 55
Array elements are: 11 22 33 44 55
Sum of all elements: 165

3.Realloc():
 By using realloc() we can create the memory dynamically at middle stage.
 Generally by using realloc() we can reallocation the memory.
 Realloc() required 2 arguments of type void*, size_type.
 Void* will indicates previous block base address, size-type is data type size.
 Realloc() will creates the memory in bytes format and initial value is garbage.
Syntax

Void *realloc(void *, sizeof(data-type));


int *arr;
arr=(int*)calloc(5, sizeof(int));
.....
........
....
arr=(int*)realloc(arr,sizeof(int)*10);

COMPUTER PROGRAMMING-II Page 21


ANURAG GROUP OF INSTITUTIONS
(CVSR COLLEGE OF ENGINEERING)

4.free():
 When we are working with dynamic memory allocation memory will created in heap
area of data segment.
 When we are working with dynamic memory allocation related memory it is a
permanent memory if we are not de-allocated that's why when we are working with
dynamic memory allocation related program, then always recommended to deleted
the memory at the end of the program.
 By using free(0 dynamic allocation memory can be de-allocated.
 free() requires one arguments of type void*.
Syntax

void free(voie*);
int *arr;
arr=(int*)calloc(10,sizeof(int));
...
......
free(arr);

DIFFERENCE BETWEEN MALLOC() AND CALLOC() FUNCTIONS IN C:


malloc() calloc()

It allocates only single block of requested It allocates multiple blocks of requested


memory memory

int *ptr;Ptr = calloc( 20, 20 * sizeof(int)


int *ptr;ptr = malloc( 20 * sizeof(int) );For );For the above, 20 blocks of memory will be
the above, 20*4 bytes of memory only created and each contains 20*4 bytes of
allocated in one block. memory.
Total = 80 bytes Total = 1600 bytes

malloc () doesn’t initializes the allocated calloc () initializes the allocated memory to
memory. It contains garbage values zero

type cast must be done since this function


returns void pointer int *ptr;ptr = Same as malloc () function int *ptr;ptr =
(int*)malloc(sizeof(int)*20 ); (int*)calloc( 20, 20 * sizeof(int) );

COMPUTER PROGRAMMING-II Page 22

S-ar putea să vă placă și