0% found this document useful (0 votes)
33 views74 pages

Pointers Inc

Uploaded by

hardik.18.kum
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views74 pages

Pointers Inc

Uploaded by

hardik.18.kum
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 74

Pointer in C

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
typecasted to any type.
▪One of the main properties of void pointers is that they cannot be dereferenced.
Syntax:
void * pointer_name;
Example Program
#include <stdio.h>
int main()
{
int a = 10;
char b = 'x';
// void pointer holds address of int 'a'
void* p = &a;
printf ("Address of a stored in void pointer p =%p\n",p);
// void pointer holds address of char 'b'
p = &b;
printf ("Address of b stored in void pointer p =%p",p);
}
OUTPUT:
Address of a stored in void pointer p =00000031163ffb74
Address of b stored in void pointer p =00000031163ffb73
▪Void pointers cannot be dereferenced #include <stdio.h>
therefore the following program int main()
doesn’t compile and gives an error.
{
▪malloc() and calloc() return void * int a = 10;
type and are used to allocate memory
of any data type. void* ptr = &a;

▪void pointers in C are used to printf("%d", *ptr);


implement generic functions in C.
return 0;
}
▪void pointer is typecasted to an integer pointer and then dereferenced to access the
value.
#include <stdio.h>

int main()
{
int a = 10;
void* ptr = &a;
// The void pointer is cast to an integer pointer using '(int*)ptr'
// Then, the value is dereferenced with `*(int*)ptr` to get the
// value at that memory location
printf("%d", *(int*)ptr);
return 0;
OUTPUT:
} 10
▪ The C standard doesn’t allow pointer arithmetic with void pointers. However, in
GNU C it is allowed by considering the size of the void as 1.
▪EXAMPLE PROGRAM
#include <stdio.h>

int main()
{
int a[2] = { 8, 6 };
// Declare a void pointer and assign the address of
// array 'a' to it
void* ptr = &a;
// Increment the pointer by the size of an integer
ptr = ptr + sizeof(int);
// The void pointer 'ptr' is typecasted to an integer
// pointer Then, the value is dereferenced get the value at
// that memory location
printf("%d", *(int*)ptr);

return 0;
}

OUTPUT: Note : The above program may not work in other compilers.
6
Pointers v/s Array
S.No. Array Pointer
1. It stores the values of a It stores the address of variables.
homogeneous data type.
2. An array is defined as a collection Pointer is a variable which stores
of similar datatypes. address of another variable.
3. The number of variables that can be Pointer can store the address of
stored is decided by the size of the only a single variable.
array.
4. The initialization of arrays can be Pointers cannot be initialized
done while defining them. while defining them.
S.No. Array Pointer
5. The nature of arrays is static. The nature of pointers is dynamic.
Arrays cannot be resized according Pointers can be resized at any
6.
to user's requirements. point of time.
The allocation of array is done at The allocation of pointer is done
7.
compile time. at run time.
Call by Value
▪we have always passed the ‘values’ of variables to the called function which is
know as call by value.
▪In call by value method of parameter passing, the values of actual parameters are
copied to the function’s formal parameters.
▪There are two copies of parameters stored in different memory locations.
▪One is the original copy and the other is the function copy.
▪Any changes made inside functions are not reflected in the actual parameters .
Program to illustrate call by value
#include <stdio.h>

// Function Prototype
void swapx(int x, int y);

int main()
{
int a = 10, b = 20;

// Pass by Values
swapx(a, b); // Actual Parameters
printf("Actual Parameters:\na = %d b = %d\n", a, b);
return 0;
}
// Swap functions that swaps
// two values
void swapx(int x, int y) // Formal Parameters
{
int t;

t = x;
x = y;
y = t;

printf("Inside Function:\nx = %d y = %d\n", x, y);


}
OUTPUT:
Inside Function:
x = 20 y = 10
Actual Parameters:
a = 10 b = 20
Call by Reference
▪Instead of passing the value of a variable, we can pass the memory address of the
variable to a function. Then it would be a ‘call by reference’.
▪Both the actual and formal parameters refer to the same locations.
▪Any changes made inside the function are actually reflected in the actual
parameters of the caller.
Program to illustrate Call by Reference
#include <stdio.h>

// Function Prototype
void swapx(int*, int*);

// Main function
int main()
{
int a = 10, b = 20;

// Pass reference
swapx(&a, &b); // Actual Parameters
printf("Actual Parameters of the caller:\na = %d b = %d\n", a, b);

return 0;
}

// Function to swap two variables


// by references
void swapx(int* x, int* y) // Formal Parameters
{
int t;

t = *x;
*x = *y;
*y = t;

printf("Inside the Function:\nx = %d y = %d\n", *x, *y);


}
OUTPUT:
Inside the Function:
x = 20 y = 10
Actual Parameters of the caller:
a = 20 b = 10
Dynamic Memory Allocation in C.
▪It is a procedure in which the size of a data structure (like Array) is changed
during the runtime.
▪C provides some functions to achieve these tasks.
▪There are 4 library functions provided by C defined under <stdlib.h> header file
to facilitate dynamic memory allocation in C programming.
1.malloc()
2.calloc()
3.free()
4.realloc()
malloc()
▪The “malloc” or “memory allocation” method in C is used to dynamically
allocate a single large block of memory with the specified size.
▪It returns a pointer of type void which can be cast into a pointer of any form.
▪It doesn’t Initialize memory at execution time so that it has initialized each block
with the default garbage value initially.
▪Syntax:
ptr = (cast-type*) malloc(byte-size);
▪The expression results in a NULL pointer if the space is insufficient and the
memory cannot be allocated.
▪Example:
ptr = (int*) malloc(100 * sizeof(int));
▪Since the size of int is 4 bytes, this statement will allocate 400 bytes of memory.
▪The pointer ptr holds the address of the first byte in the allocated memory.

ptr =
400 bytes of Memory

400 bytes of memory block is dynamically allocated to ptr


Program to illustrate malloc()
#include <stdio.h>
#include <stdlib.h>

int main()
{

// This pointer will hold the


// base address of the block created
int* ptr;
int n, i;

// Get the number of elements for the array


printf("Enter number of elements:");
scanf("%d",&n);
printf("Entered number of elements: %d\n", n);

// Dynamically allocate memory using malloc()


ptr = (int*)malloc(n * sizeof(int));

// Check if the memory has been successfully


// allocated by malloc or not
if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else {

// Memory has been successfully allocated


printf("Memory successfully allocated using malloc.\n");
printf("ENTER THE ELEMENTS IN THE MEMORY\n");

// Get the elements


for (i = 0; i < n; ++i) {
scanf("%d", ptr + i);
}

// Print the elements


printf("The elements are: ");
for (i = 0; i < n; ++i) {
printf("%d ", ptr[i]);
}
}

return 0;
}
OUTPUT:
ENTER THE ELEMENTS IN THE MEMORY
34
45
36
23
87
The elements are: 34 45 36 23 87
calloc()
▪"calloc" stands for contiguous allocation.
▪The malloc() function allocates memory and leaves the memory uninitialized,
whereas the calloc() function allocates memory and initializes all bits to zero.
▪Syntax:
ptr = (castType*)calloc(n, size);
▪Example:
ptr = (float*) calloc(25, sizeof(float));
The above statement allocates contiguous space in memory for 25 elements of
type float.
free()
▪Dynamically allocated memory created with either calloc() or malloc() doesn't
get freed on their own. You must explicitly use free() to release the space.
▪Syntax:
free(ptr);
Where ptr is the pointer to the memory block that needs to be freed or
deallocated.
▪The free() function cannot be used to free the statically allocated memory (e.g.,
local variables) or memory allocated on the stack.
Program to illustrate malloc() and free()
// Program to calculate the sum of n numbers entered by the user

#include <stdio.h>
#include <stdlib.h>

int main() {
int n, i, *ptr, sum = 0;

printf("Enter number of elements: ");


scanf("%d", &n);

ptr = (int*) malloc(n * sizeof(int));


// if memory cannot be allocated
if(ptr == NULL) {
printf("Error! memory not allocated.");
exit(0);
}

printf("Enter elements: ");


for(i = 0; i < n; ++i) {
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum); OUTPUT:
Enter number of elements: 5
// deallocating the memory
Enter elements: 34
free(ptr);
35
return 0; 67
} 18
87
Sum = 241
realloc()
▪It is used to dynamically change the memory allocation of a previously allocated
memory.
▪Re-allocation of memory maintains the already present value and new blocks
will be initialized with the default garbage value.
▪Syntax:
ptr = realloc(ptr, newSize);
where ptr is reallocated with new size 'newSize'.
Program to illustrate realloc()
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr = (int *)malloc(sizeof(int)*2);
int i; int *ptr_new;

*ptr = 10;
*(ptr + 1) = 20;
printf("elements of ptr before reallocation\n");
for(i = 0; i < 2; i++)
printf("%d ", *(ptr + i));
ptr_new = (int *)realloc(ptr, sizeof(int)*3);
*(ptr_new + 2) = 30;

printf("\nelements of ptr_new after reallocation\n");

for(i = 0; i < 3; i++)


printf("%d ", *(ptr_new + i));

return 0;
}
OUTPUT:
elements of ptr before reallocation
10 20
elements of ptr_new after reallocation
10 20 30
Pointer to an Array
#include<stdio.h> ▪In this program, A pointer ptr points to
the 0th element of the array.
int main()
▪Similarly, a pointer can be declared that
{ can point to whole array instead of only
int arr[5] = { 1, 2, 3, 4, 5 }; one element of the array.
int *ptr = arr; ▪Pointer to an array is useful when
talking about multidimensional arrays.
printf("%p\n", ptr);
return 0;
}
▪Syntax:
data_type (*var_name)[size_of_array];
▪Example:
int (*ptr)[10];
▪Here ptr is pointer that can point to an array of 10 integers.
▪Since subscript have higher precedence than indirection, it is necessary to
enclose the indirection operator and pointer name inside parentheses.
Program to illustrate difference between pointer
to an integer and pointer to an array of integers.
#include<stdio.h>

int main()
{
// Pointer to an integer
int *p;

// Pointer to an array of 5 integers


int (*ptr)[5];
int arr[5];

// Points to 0th element of the arr.


p = arr;

// Points to the whole array arr.


ptr = &arr;

printf("p = %p, ptr = %p\n", p, ptr);

p++;
ptr++;

printf("p = %p, ptr = %p\n", p, ptr);

return 0;
}
OUTPUT:
p = 000000bb7bdffbf0, ptr = 000000bb7bdffbf0
p = 000000bb7bdffbf4, ptr = 000000bb7bdffc04

▪ The base type of p is int while base type of ptr is ‘an array of 5 integers’.

▪ Pointer arithmetic is performed relative to the base size, so if we write ptr++,


then the pointer ptr will be shifted forward by 20 bytes.

❖ whenever a pointer to an array is dereferenced, we get the base address of the


array to which it points.
Array of pointers
▪Array of pointers” is an array of the pointer variables. It is also known as pointer
arrays.
▪Syntax:
int *var_name[array_size];
▪It is generally used when we want to point at multiple memory locations of a
similar data type in our program.
▪Array of pointers can also be defined for derived and user-defined data types
such as arrays, structures, etc.
Program to demonstrate example of
array of pointers.
#include <stdio.h>

const int SIZE = 3;


void main()
{

// creating an array
int arr[] = { 1, 2, 3 };

// integer pointer array to store the address of array elements

int i, *ptr[SIZE];
// assigning the address of integer.
for (i = 0; i < SIZE; i++)
ptr[i] = &arr[i];

// printing values using pointer


for (i = 0; i < SIZE; i++)
printf("Value of arr[%d] = %d\n", i, *ptr[i]);

}
OUTPUT:
Value of arr[0] = 1
Value of arr[1] = 2
Value of arr[2] = 3
Program to demonstrate array of pointers
to store a list of strings.
#include <stdio.h>

const int size = 4;


void main()
{

// array of pointers to a character


// to store a list of strings
char* names[] = {
"amit",
"amar",
"ankit",
"akhil"
};
int i = 0; OUTPUT:
amit
for (i = 0; i < size; i++)
printf("%s\n", names[i]); amar
} ankit
akhil
Program to demonstrate Array of pointers can
store addresses of other arrays.
# include <stdio.h>
int main( )
{
static int a[ ] = { 0, 1, 2, 3, 4 } ;
int *p[ ] = { a, a + 1, a + 2, a + 3, a + 4 } ;
printf ( "%u %u %d\n", p, *p, * ( *p ) ) ;
return 0 ;
}
OUTPUT:
597686848 2414575616 0

First element of array


Memory Address of the ‘a’
first element of the Memory Address of
array of pointers ‘p’ the first element of
array ‘a’.
Pointer to array versus array of pointers
Parameters Pointer to an Array Array of Pointers
Uses and A user creates a pointer for A user creates an array of pointers
Purposes storing the address of any that basically acts as an array of
given array. multiple pointer variables.
Alternative It is alternatively known as an These are alternatively known as
Names array pointer. pointer arrays.
Allocation One can allocate these during One can allocate these during the
the run time. compile time.
Initialization A pointer cannot be initialized An array can be easily initialized
at Definition at the definition. at the definition level.
Parameters Pointer to an Array Array of Pointers

Nature It is dynamic in nature. It is static in nature.


Resizing A pointer's allocated memory An array cannot be resized to fit
can be readily resized at any our needs at any point after its size
point in time. has been declared.
Type of A typical pointer variable is The size of any given array
Storage capable of storing only a single decides the total number of
variable within. variables that it can store within.
Pointer to functions.
▪A pointer to a function is used to invoke a function indirectly.
▪Syntax for declaration:
returnType (*pointerName)(parameterType1, parameterType2, ...);
▪Example:
▪int (*functionPtr)(int, int);
int is the return type of the function that the pointer will point to.
(*functionPtr) declares the pointer to the function.
(int, int) specifies that the function takes two int parameters.
▪A function pointer points to code, not data. Typically a function pointer stores the
start of executable code.
▪Function pointers are not used to create or de-allocate memory, in contrast to
regular pointers.
▪A function’s name can also be used to get functions’ address.
Example Program for pointer to function
#include <stdio.h>
int add(int a, int b) { return a + b; }

int main()
{
// Assigning function address using & operator
int (*add_ptr)(int, int) = &add;

// function address can also be assigned without & operator


//int (*add_ptr)(int, int) = add;
/* Calling the function using the function pointer*/ OUTPUT:
int result = add_ptr(3, 4); Result: 7
//function can be also called using function pointer as
//int result = (*add_ptr)(3, 4);

printf("Result: %d\n", result);

return 0;
}
▪An array of function pointers is possible, just like with regular pointers.
▪Function pointer can be used in place of switch case.
▪A function pointer can be passed as an argument and can also be returned from a
function.
Program to illustrate an array of function
pointers
#include <stdio.h>
void add(int a, int b)
{
printf("Addition is %d\n", a+b);
}
void subtract(int a, int b)
{
printf("Subtraction is %d\n", a-b);
}
void multiply(int a, int b)
{
printf("Multiplication is %d\n", a*b); }
int main()
{
// fun_ptr_arr is an array of function pointers
void (*fun_ptr_arr[])(int, int) = {add, subtract, multiply};
unsigned int ch, a = 15, b = 10;

printf("Enter Choice: 0 for add, 1 for subtract and 2 "


"for multiply\n");
scanf("%d", &ch);

if (ch > 2) return 0;

(*fun_ptr_arr[ch])(a, b);

return 0;
}
OUTPUT:
Enter Choice: 0 for add, 1 for subtract and 2 for multiply
2
Multiplication is 150
Program to illustrate function pointers as
parameter
#include <stdio.h>

void fun1() { printf("Function 1\n"); }


void fun2() { printf("Function 2\n"); }

// A function that receives a simple function pointer


// as parameter and calls the function
void wrapper(void (*fun)())
{
fun();
}
int main() OUTPUT:
{ Function 1
wrapper(fun1);
Function 2
wrapper(fun2);
return 0;
}
Program to illustrate a function returning
a pointer
#include <stdio.h>
int* findLarger(int*, int*);
void main()
{
int numa=0;
int numb=0;
int *result;

printf(" Input the first number : ");


scanf("%d", &numa);
printf(" Input the second number : ");
scanf("%d", &numb);
result=findLarger(&numa, &numb);
printf(" The number %d is larger. \n\n",*result);
}

int* findLarger(int *n1, int *n2)


{
if(*n1 > *n2)
return n1;
else
return n2;
}
OUTPUT:
Input the first number : 45
Input the second number : 67
The number 67 is larger.
Program to print all permutations of a
given string using pointers.
#include <stdio.h>
#include <string.h>

void changePosition(char *ch1, char *ch2)


{
char tmp;
tmp = *ch1;
*ch1 = *ch2;
*ch2 = tmp;
}
void charPermu(char *cht, int stno, int endno)
{
int i;
if (stno == endno)
printf("%s ", cht);
else
{
for (i = stno; i <= endno; i++)
{
changePosition((cht+stno), (cht+i));
charPermu(cht, stno+1, endno);
changePosition((cht+stno), (cht+i));
}
}
}
int main()
{
char str[] = "mnit";
printf("\n\n Permutations of a given string :\n");
printf("--------------------------------------------------------\n");
int n = strlen(str);
printf(" The permutations of the string are : \n");
charPermu(str, 0, n-1);
printf("\n\n");
return 0;
}
OUTPUT:
Permutations of a given string :
--------------------------------------------------------
The permutations of the string are :
mnit mnti mint mitn mtin mtni nmit nmti nimt nitm
ntim ntmi inmt intm imnt imtn itmn itnm tnim tnmi
tinm timn tmin tmni
Program to find the largest element using
Dynamic Memory Allocation
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i,n;
float *element;
printf(" Input total number of elements(1 to 100): ");
scanf("%d",&n);
element=(float*)calloc(n,sizeof(float));
// Memory is allocated for 'n' elements
if(element==NULL)
{
printf(" No memory is allocated.");
exit(0);
}
printf("\n");
for(i=0;i<n;++i)
{
printf(" Number %d: ",i+1);
scanf("%f",element+i);
}
for(i=1;i<n;++i)
{
if(*element<*(element+i))
*element=*(element+i);
}
printf(" The Largest element is : %.2f \n\n",*element);
return 0;
}
OUTPUT:
Input total number of elements(1 to 100): 5

Number 1: 34
Number 2: 45
Number 3: 36
Number 4: 28
Number 5: 89
The Largest element is : 89.00
Program to sort an array using pointer
#include <stdio.h>
void main()
{
int *a,i,j,tmp,n;

printf(" Input the number of elements to store in the array : ");


scanf("%d",&n);

printf(" Input %d number of elements in the array : \n",n);


for(i=0;i<n;i++)
{
printf(" element - %d : ",i+1);
scanf("%d",a+i);
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if( *(a+i) > *(a+j))
{
tmp = *(a+i);
*(a+i) = *(a+j);
*(a+j) = tmp;
}
}
}
printf("\n The elements in the array after sorting : \n");
for(i=0;i<n;i++)
{
printf(" element - %d : %d \n",i+1,*(a+i));
}
printf("\n");
}
OUTPUT:
Input the number of elements to store in the array : 5
Input 5 number of elements in the array :
element - 1 : 56
element - 2 : 32
element - 3 : 78
element - 4 : 37
element - 5 : 33

The elements in the array after sorting :


element - 1 : 32
element - 2 : 33
element - 3 : 37
element - 4 : 56
element - 5 : 78

You might also like