Pointer and Dynamic Memory Allocation
Pointer and Dynamic Memory Allocation
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
Declaration of Pointer
data_type* pointer_variable_name;
int* p;
Note: void type pointer works with all data types, but isn't used often.
int a = 10 ;
or,
float a;
int *ptr;
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.
& 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 (*).
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;
Normal variable stores the value whereas pointer variable stores the address of the
variable.
* symbol is used to get the value of the variable that the pointer is pointing to.
Two pointers can be subtracted to know how many elements are available between these
two pointers.
#include <stdio.h>
#include <conio.h>
void main(){
int number=50;
int *p;
clrscr();
getch();
Output
Value of p variable is 50
Example:
#include <stdio.h>
int main()
int *ptr, q;
q = 50;
ptr = &q;
printf("%d", *ptr);
return 0;
Output
50
Example:
#include <stdio.h>
int main()
int *p;
p= &var;
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:
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.
int **p2;
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;
clrscr();
p2=&p;
getch();
Output
Value of *p variable is 50
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
int arr[5]={ 1, 2, 3, 4, 5 };
int *p;
p = arr;
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;
printf("%d", *p);
p++;
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.
Since, the addresses of both are the same, the values of arr and &arr[0] are also the same.
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");
scanf("%d",(classes + i));
return 0;
Output
Sum = 21
o Increment(++)
o Decrement(--)
o Addition(+)
o Subtraction(-)
Increment pointer:
Address + 1 = Address
Address++ = Address
Pictorial Representation :
Note :
32 bit
64 bit
Example:
#include <stdio.h>
void main(){
int number=50;
p=p+1;
Output
Decrement(--)
Example:
#include <stdio.h>
void main(){
int number=50;
p=p-1;
Output
Addition(+)
Note:
32 bit
64 bit
Example:
#include <stdio.h>
void main(){
int number=50;
Output
Subtraction (-)
Like pointer addition, we can subtract a value from the pointer variable. The formula
of subtracting value from pointer variable.
Example:
#include <stdio.h>
void main(){
int number=50;
Output
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.
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};
int i;
double avg;
double sum = 0;
return avg;
}
Output
Average value is: 214.400000
disp (arr[x]);
}
return 0;
}
Output:
abcdefghij
#include <stdio.h>
int main()
disp (&arr[i]);
return 0;
Output:
1234567890
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:
Example
int *ptr[MAX];
alpha[0] *a
alpha[1] *(a+1)
alpha[2] *(a+2)
alpha[3] *(a+3)
alpha[n] *(a+n)
Example1:
#include <stdio.h>
int main () {
int i, *ptr[MAX];
return 0;
Output
Value of var[0] = 10
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();
Output
Example3:
#include <stdio.h>
int main () {
char *names[] = {
"Zara Ali",
"Hina Ali",
"Nuha Ali",
"Sara Ali"
};
int i = 0;
return 0;
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]);
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.
int var1;
void * pointer_name;
char cnum;
int inum;
float fnum;
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:
1)
#include<stdio.h>
int main()
int a = 10;
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;
}
Scenario Behavior
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)
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
Example
struct employee
{
char *name;
int salary;
};
typedef struct employee emp;
emp *e1;
e1 = (emp*)calloc(30,sizeof(emp));
calloc() malloc()
calloc() initializes the allocated memory with malloc() initializes the allocated memory with garbage
0 value. values.
Syntax : Syntax :
(cast_type *)calloc(blocks , size_of_block); (cast_type *)malloc(Size_in_bytes);
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
Example
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, i, *ptr, sum = 0;