POINTERS:
Introduction
Definition:
Pointer is a variable that stores/hold address of another variable of same data type/ t is
also known as locator or indicator that points to an address of a value. A pointer is a
derived data type in C
Benefit of using pointers
Pointers are more efficient in handling Array and Structure.
Pointer allows references to function and thereby helps in passing of function as
arguments to other function.
It reduces length and the program execution time.
It allows C to support dynamic memory management.
Declaration of Pointer
data_type* pointer_variable_name;
int* p;
Note: void type pointer works with all data types, but isn't used often.
Initialization of Pointer variable
Pointer Initialization is the process of assigning address of a variable to pointer variable.
Pointer variable contains address of variable of same data type
int a = 10 ;
int *ptr ; //pointer declaration
ptr = &a ; //pointer initialization
or,
C PROGRAMMING Page 197
int *ptr = &a ; //initialization and declaration together
Note:Pointer variable always points to same type of data.
float a;
int *ptr;
ptr = &a; //ERROR, type mismatch
Above statement defines, p as pointer variable of type int. Pointer example
As you can see in the above figure, pointer variable stores the address of number variable i.e.
fff4. The value of number variable is 50. But the address of pointer variable p is aaa3.
By the help of * (indirection operator), we can print the value of pointer variable p.
Reference operator (&) and Dereference operator (*)
& is called reference operator. It gives you the address of a variable. There is another operator
that gets you the value from the address, it is called a dereference operator (*).
Symbols used in pointer
Symbol Name Description
& (ampersand sign) address of operator determines the address of a variable.
* (asterisk sign) indirection operator accesses the value at the address.
C PROGRAMMING Page 198
Dereferencing of Pointer
Once a pointer has been assigned the address of a variable. To access the value of variable,
pointer is dereferenced, using the indirection operator *.
int a,*p;
a = 10;
p = &a;
printf("%d",*p); //this will print the value of a.
printf("%d",*&a); //this will also print the value of a.
printf("%u",&a); //this will print the address of a.
printf("%u",p); //this will also print the address of a.
printf("%u",&p); //this will also print the address of p.
KEY POINTS TO REMEMBER ABOUT POINTERS IN C:
Normal variable stores the value whereas pointer variable stores the address of the
variable.
The content of the C pointer always be a whole number i.e. address.
Always C pointer is initialized to null, i.e. int *p = null.
The value of null pointer is 0.
& symbol is used to get the address of the variable.
* symbol is used to get the value of the variable that the pointer is pointing to.
If a pointer in C is assigned to NULL, it means it is pointing to nothing.
Two pointers can be subtracted to know how many elements are available between these
two pointers.
But, Pointer addition, multiplication, division are not allowed.
The size of any pointer is 2 byte (for 16 bit compiler).
C PROGRAMMING Page 199
Example:
#include <stdio.h>
#include <conio.h>
void main(){
int number=50;
int *p;
clrscr();
p=&number;//stores the address of number variable
printf("Address of number variable is %x \n",&number);
printf("Address of p variable is %x \n",p);
printf("Value of p variable is %d \n",*p);
getch();
Output
Address of number variable is fff4
Address of p variable is fff4
Value of p variable is 50
Example:
#include <stdio.h>
int main()
int *ptr, q;
q = 50;
C PROGRAMMING Page 200
/* address of q is assigned to ptr */
ptr = &q;
/* display q's value using ptr variable */
printf("%d", *ptr);
return 0;
Output
50
Example:
#include <stdio.h>
int main()
int var =10;
int *p;
p= &var;
printf ( "\n Address of var is: %u", &var);
printf ( "\n Address of var is: %u", p);
printf ( "\n Address of pointer p is: %u", &p);
/* Note I have used %u for p's value as it should be an address*/
printf( "\n Value of pointer p is: %u", p);
printf ( "\n Value of var is: %d", var);
printf ( "\n Value of var is: %d", *p);
printf ( "\n Value of var is: %d", *( &var));
C PROGRAMMING Page 201
Output:
Address of var is: 00XBBA77
Address of var is: 00XBBA77
Address of pointer p is: 77221111
Value of pointer p is: 00XBBA77
Value of var is: 10
Value of var is: 10
Value of var is: 10
NULL Pointer
A pointer that is not assigned any value but NULL is known as NULL pointer. If you don't have
any address to be specified in the pointer at the time of declaration, you can assign NULL value.
Or
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.int *p=NULL;
Note: The NULL pointer is a constant with a value of zero defined in several standard libraries/
in most the libraries, the value of pointer is 0 (zero)
Example:
The value of ptr is 0
Pointers for Inter Function Communication
Pointers to Pointers
Pointers can point to other pointers /pointer refers to the address of another pointer.
pointer can point to the address of another pointer which points to the address of a value.
C PROGRAMMING Page 202
syntax of pointer to pointer
int **p2;
pointer to pointer example
Let's see an example where one pointer points to the address of another pointer.
Example:
#include <stdio.h>
#include <conio.h>
void main(){
int number=50;
int *p;//pointer to int
int **p2;//pointer to pointer
clrscr();
p=&number;//stores the address of number variable
p2=&p;
printf("Address of number variable is %x \n",&number);
printf("Address of p variable is %x \n",p);
C PROGRAMMING Page 203
printf("Value of *p variable is %d \n",*p);
printf("Address of p2 variable is %x \n",p2);
printf("Value of **p2 variable is %d \n",**p);
getch();
Output
Address of number variable is fff4
Address of p variable is fff4
Value of *p variable is 50
Address of p2 variable is fff2
Value of **p variable is 50
Arrays and Pointers
When an array is declared, compiler allocates sufficient amount of memory to contain all the
elements of the array. Base address which gives location of the first element is also allocated by
the compiler.
Suppose we declare an array arr,
int arr[5]={ 1, 2, 3, 4, 5 };
Assuming that the base address of arr is 1000 and each integer requires two byte, the five
element will be stored as follows
C PROGRAMMING Page 204
Here variable arr will give the base address, which is a constant pointer pointing to the
element, arr[0]. Therefore arr is containing the address of arr[0] i.e 1000.
arr is equal to &arr[0] // by default
We can declare a pointer of type int to point to the array arr.
int arr[5]={ 1, 2, 3, 4, 5 };
int *p;
p = arr;
or p = &arr[0]; //both the statements are equivalent.
Now we can access every element of array arr using p++ to move from one element to another.
NOTE : You cannot decrement a pointer once incremented. p-- won't work.
Pointer to Array
we can use a pointer to point to an Array, and then we can use that pointer to access the array.
Lets have an example,
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // same as int*p = &a[0]
for (i=0; i<5; i++)
printf("%d", *p);
p++;
C PROGRAMMING Page 205
In the above program, the pointer *p will print all the values stored in the array one by one. We
can also use the Base address (a in above case) to act as pointer and print all the values.
Relation between Arrays and Pointers
Consider an array:
int arr[4];
In C programming, name of the array always points to address of the first element of an array.
In the above example, arr and &arr[0] points to the address of the first element.
&arr[0] is equivalent to arr
Since, the addresses of both are the same, the values of arr and &arr[0] are also the same.
arr[0] is equivalent to *arr (value of an address of the pointer)
C PROGRAMMING Page 206
Similarly,
&arr[1] is equivalent to (arr + 1) AND, arr[1] is equivalent to *(arr + 1).
&arr[2] is equivalent to (arr + 2) AND, arr[2] is equivalent to *(arr + 2).
&arr[3] is equivalent to (arr + 3) AND, arr[3] is equivalent to *(arr + 3).
&arr[i] is equivalent to (arr + i) AND, arr[i] is equivalent to *(arr + i).
Example: Program to find the sum of six numbers with arrays and pointers
#include <stdio.h>
int main()
int i, classes[6],sum = 0;
printf("Enter 6 numbers:\n");
for(i = 0; i < 6; ++i)
// (classes + i) is equivalent to &classes[i]
scanf("%d",(classes + i));
// *(classes + i) is equivalent to classes[i]
sum += *(classes + i);
printf("Sum = %d", sum);
return 0;
Output
C PROGRAMMING Page 207
Enter 6 numbers:
Sum = 21
Pointer Arithmetic and Arrays
pointer holds address of a value, so there can be arithmetic operations on the pointer variable.
There are four arithmetic operators that can be used on pointers:
o Increment(++)
o Decrement(--)
o Addition(+)
o Subtraction(-)
Increment pointer:
1. Incrementing Pointer is generally used in array because we have contiguous memory in
array and we know the contents of next memory location.
2. Incrementing Pointer Variable Depends Upon data type of the Pointer variable.
The formula of incrementing pointer is given below:
new_address= current_address + i * size_of(data type)
Three rules should be used to increment pointer
Address + 1 = Address
Address++ = Address
C PROGRAMMING Page 208
++Address = Address
Pictorial Representation :
Data Older Address stored Next Address stored in pointer after
Type in pointer incrementing (ptr++)
int 1000 1002
float 1000 1004
char 1000 1001
Note :
32 bit
For 32 bit int variable, it will increment to 2 byte.
64 bit
For 64 bit int variable, it will increment to 4 byte.
Example:
#include <stdio.h>
void main(){
int number=50;
C PROGRAMMING Page 209
int *p;//pointer to int
p=&number;//stores the address of number variable
printf("Address of p variable is %u \n",p);
p=p+1;
printf("After increment: Address of p variable is %u \n",p);
Output
Address of p variable is 3214864300
After increment: Address of p variable is 3214864304
Decrement(--)
Like increment, we can decrement a pointer variable.
formula of decrementing pointer
new_address= current_address - i * size_of(data type)
Example:
#include <stdio.h>
void main(){
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
printf("Address of p variable is %u \n",p);
p=p-1;
C PROGRAMMING Page 210
printf("After decrement: Address of p variable is %u \n",p);
Output
Address of p variable is 3214864300
After decrement: Address of p variable is 3214864296
Addition(+)
We can add a value to the pointer variable.
formula of adding value to pointer
new_address= current_address + (number * size_of(data type))
Note:
32 bit
For 32 bit int variable, it will add 2 * number.
64 bit
For 64 bit int variable, it will add 4 * number.
Example:
#include <stdio.h>
void main(){
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
printf("Address of p variable is %u \n",p);
C PROGRAMMING Page 211
p=p+3; //adding 3 to pointer variable
printf("After adding 3: Address of p variable is %u \n",p);
Output
Address of p variable is 3214864300
After adding 3: Address of p variable is 3214864312
Subtraction (-)
Like pointer addition, we can subtract a value from the pointer variable. The formula
of subtracting value from pointer variable.
new_address= current_address - (number * size_of(data type))
Example:
#include <stdio.h>
void main(){
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
printf("Address of p variable is %u \n",p);
p=p-3; //subtracting 3 from pointer variable
printf("After subtracting 3: Address of p variable is %u \n",p);
Output
C PROGRAMMING Page 212
Address of p variable is 3214864300
After subtracting 3: Address of p variable is 3214864288
Passing an Array to a Function
If you want to pass a single-dimension array as an argument in a function, you would have to
declare a formal parameter in one of following three ways and all three declaration methods
produce similar results because each tells the compiler that an integer pointer is going to be
received. Similarly, you can pass multi-dimensional arrays as formal parameters.
1) Formal parameters as a pointer
void myFunction(int *param) {
.
.
.
}
2) Formal parameters as a sized array
void myFunction(int param[10]) {
.
.
.
}
3)
void myFunction(int param[10]) {
.
.
.
}
Example1: pass an entire array to a function argument
#include <stdio.h>
/* function declaration */
double getAverage(int arr[], int size);
int main () {
/* an int array with 5 elements */
int balance[5] = {1000, 2, 3, 17, 50};
C PROGRAMMING Page 213
double avg;
/* pass pointer to the array as an argument */
avg = getAverage( balance, 5 ) ;
/* output the returned value */
printf( "Average value is: %f ", avg );
return 0;
}
double getAverage(int arr[], int size) {
int i;
double avg;
double sum = 0;
for (i = 0; i < size; ++i) {
sum += arr[i];
}
avg = sum / size;
return avg;
}
Output
Average value is: 214.400000
Example2: pass an entire array to a function argument
#include <stdio.h>
myfuncn( int *var1, int var2)
{
for(int x=0; x<var2; x++)
{
printf("Value of var_arr[%d] is: %d \n", x, *var1);
/*increment pointer for next element fetch*/
var1++;
}
}
C PROGRAMMING Page 214
int main()
{
int var_arr[] = {11, 22, 33, 44, 55, 66, 77};
myfuncn(&var_arr, 7);
return 0;
}
Output
Value of var_arr[0] is: 11
Value of var_arr[1] is: 22
Value of var_arr[2] is: 33
Value of var_arr[3] is: 44
Value of var_arr[4] is: 55
Value of var_arr[5] is: 66
Value of var_arr[6] is: 77
Example: Call by value method
#include <stdio.h>
disp( char ch)
{
printf("%c ", ch);
}
int main()
{
char arr[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'I', 'j'};
for (int x=0; x<=10; x++)
{
disp (arr[x]);
}
return 0;
}
Output:
abcdefghij
C PROGRAMMING Page 215
In this method of calling a function, the actual arguments gets copied into formal
arguments. In this example actual argument(or parameter) is arr[x] and formal parameter
is ch.
Example: Call by reference method: Using pointers
#include <stdio.h>
disp( int *num)
printf("%d ", *num);
int main()
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
for (int i=0; i<=10; i++)
disp (&arr[i]);
return 0;
Output:
1234567890
C PROGRAMMING Page 216
Array of Pointers
An array of pointers would be an array that holds memory locations. An array of pointers is an
indexed set of variables in which the variables are pointers (a reference to a location in memory).
Syntax:
data_type_name * variable name
Example
int *ptr[MAX];
Array alpha[] Pointer a
alpha[0] *a
alpha[1] *(a+1)
alpha[2] *(a+2)
alpha[3] *(a+3)
alpha[n] *(a+n)
Example1:
#include <stdio.h>
const int MAX = 3;
int main () {
int var[] = {10, 100, 200};
int i, *ptr[MAX];
for ( i = 0; i < MAX; i++) {
C PROGRAMMING Page 217
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
Example2:
#include <stdio.h>
#include <conio.h>
main() {
clrscr();
int *array[3];
int x = 10, y = 20, z = 30;
int i;
array[0] = &x;
array[1] = &y;
array[2] = &z;
for (i=0; i< 3; i++) {
printf("The value of %d= %d ,address is %u\t \n", i, *(array[i]),
array[i]);
}
getch();
C PROGRAMMING Page 218
return 0;
}
Output
Example3:
#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;
C PROGRAMMING Page 219
Output:
Value of names[0] = Zara Ali
Value of names[1] = Hina Ali
Value of names[2] = Nuha Ali
Value of names[3] = Sara Ali
Example4:
#include <stdio.h>
int main()
char *fruit[] = {
"watermelon",
"banana",
"pear",
"apple",
"coconut",
"grape",
"blueberry"
};
int x;
for(x=0;x<7;x++)
puts(fruit[x]);
C PROGRAMMING Page 220
return(0);
Pointers to Void and to Functions
Pointers to Void
Note:
1. Suppose we have to declare integer pointer, character pointer and float pointer then we
need to declare 3 pointer variables.
2. Instead of declaring different types of pointer variable it is feasible to declare single
pointer variable which can act as integer pointer,character pointer.
A pointer variable declared using a particular data type can not hold the location address of
variables of other data types. It is invalid and will result in a compilation error.
Ex:- char *ptr;
int var1;
Here comes the importance of a . A void pointer is nothing but a pointer
vari
Void Pointer Basics :
3. In C General Purpose Pointer is called as void Pointer.
4. It does not have any data type associated with it
5. It can store address of any type of variable
6. A void pointer is a C convention for a raw address.
7. The compiler has no idea what type of object a void Pointer really points to ?
C PROGRAMMING Page 221
Void pointer: 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 typcasted to any type. Special type of pointer called
void pointer or general purpose pointer.
Declaration of void pointer
void * pointer_name;
Void pointer example
void *ptr; // ptr is declared as Void pointer
char cnum;
int inum;
float fnum;
ptr = &cnum; // ptr has address of character data
ptr = &inum; // ptr has address of integer data
ptr = &fnum; // ptr has address of float data
Advantages of void pointers:
1) malloc() and calloc() return void * type and this allows these functions to be used to allocate
memory of any data type (just because of void *)
int main(void)
// Note that malloc() returns void * which can be
// typecasted to any type like int *, char *, ..
C PROGRAMMING Page 222
int *x = malloc(sizeof(int) * n);
2) void pointers in C are used to implement generic functions in C.
Note:
1)
#include<stdio.h>
int main()
int a = 10;
void *ptr = &a;
printf("%d", *ptr);
return 0;
}
Output:
Compiler Error: 'void*' is not a pointer-to-object type
The following program compiles and runs fine.
#include<stdio.h>
int main()
{
int a = 10;
void *ptr = &a;
printf("%d", *(int *)ptr);
return 0;
}
C PROGRAMMING Page 223
Output:
10
Summary : Void Pointer
Scenario Behavior
When We assign address of integer variable to Void Pointer Becomes Integer
void pointer Pointer
When We assign address of character variable to Void Pointer Becomes Character
void pointer Pointer
When We assign address of floating variable to Void Pointer Becomes Floating
void pointer Pointer
Pointers to functions/ Function Pointers
A pointer to a function points to the address of the executable code of the function.
We can use pointers to call functions and to pass functions as arguments to other
functions.
We cannot perform pointer arithmetic on pointers to functions.
The type of a pointer to a function is based on both the return type and parameter types of
the function.
A declaration of a pointer to a function must have the pointer name in parentheses.
The function call operator () has a higher precedence than the dereference operator *.
Without them, the compiler interprets the statement as a function that returns a pointer to
a specified return type.
declare Pointer to function?
<function return type>(*<Pointer_name>)(function argument list)
For example
For example:
1) int *f(int a); /* function f returning an int * */
C PROGRAMMING Page 224
In this declaration, f is interpreted as a function that takes an int as argument, and returns a
pointer to an int.
2) 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:
#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
You would have noticed that the output of both the statements is same
f2p(10, 13) == sum(10, 13)
which means in generic sense you can write it out as:
pointer_name(argument list) == function(same argument list)
C PROGRAMMING Page 225
wherein pointer_name is declared as:
return_type(*pointer_name)(argument list);
pointer_name = function_name(argument list);
Memory Allocation Functions
The concept of dynamic memory allocation in c language enables the C programmer to
allocate memory at runtime.
Or
The process of allocating memory at runtime is known as dynamic memory allocation. Library
routines known as "memory management functions" are used for allocating and freeing memory
during execution of a program. These functions are defined in stdlib.h.
Dynamic memory allocation in c language is possible by 4 functions of stdlib.h header file.
1. malloc()
2. calloc()
3. realloc()
4. free()
Difference between static memory allocation and dynamic memory allocation.
static memory allocation dynamic memory allocation
memory is allocated at compile time. memory is allocated at run time.
memory can't be increased while memory can be increased while
executing program. executing program.
used in array. used in linked list.
C PROGRAMMING Page 226
Methods used for dynamic memory allocation.
malloc() allocates single block of requested memory.
calloc() allocates multiple block of requested memory.
realloc() reallocates the memory occupied by malloc() or calloc() functions.
free() frees the dynamically allocated memory.
Note: Dynamic memory allocation related function can be applied for any data type that's why
dynamic memory allocation related functions return void*.
Memory Allocation Process
Global variables, static variables and program instructions get their memory
in permanent storage area whereas local variables are stored in area called Stack. The memory
space between these two region is known as Heap area. This region is used for dynamic memory
allocation during execution of the program. The size of heap keep changing.
malloc()
malloc stands for "memory allocation".
The malloc() function allocates single block of requested memory at runtime. This function
reserves a block of memory of given size and returns a pointer of type void. This means that we
can assign it to any type of pointer using typecasting. It doesn't initialize memory at execution
time, so it has garbage value initially. If it fails to locate enough space (memory) it returns a
NULL pointer.
syntax
ptr=(cast-type*)malloc(byte-size)
Example
int *x;
x = (int*)malloc(100 * sizeof(int)); //memory space allocated to variable x
free(x); //releases the memory allocated to variable x
C PROGRAMMING Page 227
This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes respectively
and the pointer points to the address of first byte of memory.
Example
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &num);
ptr = (int*) malloc(num * sizeof(int)); //memory allocated using malloc
if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements of array: ");
for(i = 0; i < num; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
free(ptr);
return 0;
}
C PROGRAMMING Page 228
calloc()
calloc stands for "contiguous allocation".
Calloc() is another memory allocation function that is used for allocating memory at
runtime. calloc function is normally used for allocating memory to derived data types such
as arrays and structures. The calloc() function allocates multiple block of requested memory.
It initially initialize (sets) all bytes to zero.If it fails to locate enough space( memory) it returns a
NULL pointer. The only difference between malloc() and calloc() is that, malloc() allocates
single block of memory whereas calloc() allocates multiple blocks of memory each of same size.
Syntax
ptr = (cast-type*)calloc(n/number, element-size);
calloc() required 2 arguments of type count, size-type.
Count will provide number of elements; size-type is data type size
Example
int*arr;
arr=(int*)calloc(10, sizeof(int)); // 20 byte
cahr*str;
str=(char*)calloc(50, siceof(char)); // 50 byte
Example
struct employee
{
char *name;
int salary;
};
typedef struct employee emp;
emp *e1;
e1 = (emp*)calloc(30,sizeof(emp));
C PROGRAMMING Page 229
Example
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &num);
ptr = (int*) calloc(num, sizeof(int));
if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements of array: ");
for(i = 0; i < num; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
free(ptr);
return 0;
}
C PROGRAMMING Page 230
Diffrence between malloc() and calloc()
calloc() malloc()
calloc() initializes the allocated memory with malloc() initializes the allocated memory with garbage
0 value. values.
Number of arguments is 2 Number of argument is 1
Syntax : Syntax :
(cast_type *)calloc(blocks , size_of_block); (cast_type *)malloc(Size_in_bytes);
realloc(): changes memory size that is already allocated to a variable.
Or
If the previously allocated memory is insufficient or more than required, you can change the
previously allocated memory size using realloc().
If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by
realloc() function. In short, it changes the memory size. 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
ptr=realloc(ptr, new-size)
Example
int *x;
x=(int*)malloc(50 * sizeof(int));
x=(int*)realloc(x,100); //allocated a new memory to variable x
C PROGRAMMING Page 231
Example
void*realloc(void*, size-type);
int *arr;
arr=(int*)calloc(5, sizeof(int));
.....
........
....
arr=(int*)realloc(arr,sizeof(int)*10);
Example:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr, i , n1, n2;
printf("Enter size of array: ");
scanf("%d", &n1);
ptr = (int*) malloc(n1 * sizeof(int));
printf("Address of previously allocated memory: ");
for(i = 0; i < n1; ++i)
printf("%u\t",ptr + i);
printf("\nEnter new size of array: ");
scanf("%d", &n2);
ptr = realloc(ptr, n2);
for(i = 0; i < n2; ++i)
printf("%u\t", ptr + i);
return 0;
}
C PROGRAMMING Page 232
free()
When your program comes out, operating system automatically release all the memory allocated
by your program but as a good practice when you are not in need of memory anymore then you
should release that memory by calling the function free().
The memory occupied by malloc() or calloc() functions must be released by calling free()
function. Otherwise, it will consume memory until program exit.
Or
Dynamically allocated memory created with either calloc() or malloc() doesn't get freed on its
own. You must explicitly use free() to release the space.
Syntax:
free(ptr);
Example
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &num);
ptr = (int*) malloc(num * sizeof(int)); //memory allocated using malloc
if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements of array: ");
for(i = 0; i < num; ++i)
{
scanf("%d", ptr + i);
C PROGRAMMING Page 233