0% found this document useful (0 votes)
3 views

Pointer

The document provides an overview of pointers in C, including their definition, declaration, initialization, advantages, disadvantages, and types. It explains how pointers store memory addresses, the significance of the indirection operator, and the differences between null and void pointers. Additionally, it covers the implications of dangling pointers and constant pointers, along with examples and use cases for better understanding.

Uploaded by

nitinchavda2615
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Pointer

The document provides an overview of pointers in C, including their definition, declaration, initialization, advantages, disadvantages, and types. It explains how pointers store memory addresses, the significance of the indirection operator, and the differences between null and void pointers. Additionally, it covers the implications of dangling pointers and constant pointers, along with examples and use cases for better understanding.

Uploaded by

nitinchavda2615
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 108

SUBJECT : Advance - C

Topic : Pointer

By Prof. Radhika Shrimankar 1


Memory Address

• When a variable is created in C, a memory address is assigned to the


variable.

• The memory address is the location of where the variable is stored on the
computer.

• When we assign a value to the variable, it is stored in this memory


address.

• To access it, use the reference operator (&), and the result will represent
where the variable is stored: By Prof. Radhika Shrimankar
Print memory Address
int main()
{
int c = 12;
printf("%u", &c);
return 0;
}

Note:
• The memory address is in hexadecimal form (0x..). You probably won't get the
same result in your program.
• %p control string prints the argument as a memory address in hexadecimal form.
• %u prints memory address in decimal form.
By Prof. Radhika Shrimankar
Define Pointer
• The pointer is a special type of variable, which points (stores) address of
another variable.
• It provides direct access to memory. Using the pointer variable you can
store the address of another simple variable even you can access/edit
the value of that variable.
• For example, an integer variable holds (or you can say stores) an integer
value or address of a integer variable.

By Prof. Radhika Shrimankar


Declare Pointer
• A pointer variable declares followed by an asterisk sign (*).
Syntax :-
datatype *pointer varname;
int* a; //integer pointer variable
float* b; // float pointer variable
char* c; // character pointer variable

Note :- Each pointer variable takes 2 bytes (in 16 bytes compilers)/ 4 bytes (in 32 bytes
compilers) in the memory

By Prof. Radhika Shrimankar


Size of Pointer
• A pointer is a variable that stores the address of another variable.
• A possible guess is that the size will be the same as that of the variable whose address
the pointer is storing, but it’s not.
• The size of the pointer in “C” is not fixed, and it depends on certain factors.
• In C size of a pointer is not fixed as it depends on Word size of the processor.
• The size of a pointer in C depends on the factors like Processor word size and CPU
Architecture.
• Size of pointer
• 32-bit computer machine 4 bytes
• 64-bit computer machine 8 bytes
• 16-bit computer machine 2 bytes
• To find size of pointer, we follow following syntax.
• sizeof(pointer variable)

By Prof. Radhika Shrimankar


Size of Pointer
#include <stdio.h>
int main()
{
int *p;
float *q;
double *r;
printf(“\n the size of integer pointer is %d”,sizeof(p));
printf(“\n the size of fl oat pointer is %d”,sizeof(q));
printf(“\n the size of double pointer is %d”,sizeof(r));
printf(“\n the size of character pointer is %d”,sizeof(char *));
return 0;
}

By Prof. Radhika Shrimankar


Initialization of a pointer variable
Each pointer variable must be initialized with the valid address of
another variable. Since a pointer contains the address only, so you
can not assign a value directly in it.
Two ways to initialize a pointer variable :-
1) Initialization with declaration
data-type *pointer-variable= &another-variable;

2) Initialization after declaration


data-type *pointer-variable;
pointer-variable= &another-variable;
By Prof. Radhika Shrimankar
1) First Way :-
int a; Wrong Way to assign a value.
int *p=&a; 1) int *p=5;
2) Second Way 2) int *p=a;

int a;
int *p;
p = &a;

By Prof. Radhika Shrimankar


Advantages of pointer
• Pointer provide direct access to memory.
• It reduces the execution time of the program.
• It save memory space.
• It provide a way to return more than one value to functions.
• It reduces the storage space and complexity of the program.
• It provides an alternate way to access array elements.
• Pointer helps us to build complex data structure like link list, tree, graph
etc.

By Prof. Radhika Shrimankar


Advantages of pointer
Advantage Description Example/Use Case

Dynamic Memory Pointers enable dynamic memory allocation using


int *ptr = (int *)malloc(5 * sizeof(int));
Allocation functions like malloc(), calloc(), and free().

Pointers allow direct access to array elements using


Efficient Array int arr[3] = {10, 20, 30}; int *p = arr;
arithmetic, making operations faster and more
Management printf("%d", *(p + 1)); // Output: 20
efficient.
Pointers allow functions to modify variables directly
void update(int *p) { *p = 100; } int x = 10;
Pass by Reference by passing their memory addresses (pass by
update(&x); printf("%d", x); // Output: 100
reference).
int table[2][2] = {{1, 2}, {3, 4}}; int *p =
Accessing Multi- Pointers simplify navigation and operations on
&table[0][0]; printf("%d", *(p + 2)); // Output:
Dimensional Arrays multi-dimensional arrays (tables).
3
Returning Multiple Values Pointers enable a function to return multiple values void swap(int *a, int *b) { int temp = *a; *a =
from Functions by modifying variables passed to it. *b; *b = temp; }

By Prof. Radhika Shrimankar


Advantages of pointer
Advantage Description Example/Use Case
Pointers allow for efficient use of memory by working
Memory Efficiency directly with memory addresses and enabling dynamic int *arr = (int *)malloc(n * sizeof(int));
resizing.

Pointers are essential in implementing dynamic data struct Node { int data; struct Node *next;
Data Structures
structures like linked lists, stacks, queues, and trees. };

Allows calling different functions dynamically, useful in


Pointer to Functions void (*fptr)(int) = &print; (*fptr)(10);
callbacks and function tables.

Pointers enable interaction with hardware through direct


volatile int *port = (int *)0xFF00; *port =
Hardware Access memory access, crucial in embedded and system-level
0x01;
programming.

By passing references instead of copies of large data Passing arrays or structures to functions is
Reduces Code
structures, pointers reduce overhead and improve more efficient using pointers than copying
Complexity
performance. th

By Prof. Radhika Shrimankar


Advantages of pointer
• Generally, we declare memory to variables at the compile time but there
is a problem either we need more memory or we occupy extra memory
space. Using the pointers we can allocate memory to the variable at run
time and of course, we can resize it while execution time.
• So that it allows to resize the dynamically allocated memory block.
• Generally, we can not change the value of a variable in a function (call
by value) but using pointers (call by reference) we can change the actual
values of the parameters.
• Pointers allow direct memory access.

By Prof. Radhika Shrimankar


Disadvantages of pointer
• Pointer are slower than normal variables.
• Uninitialized pointer might cause segmentation fault.
• Dynamically allocated block needs to be freed explicitly. Otherwise, it
would lead to memory task.
• If pointer bugs are updated with incorrect values, it might lead to
memory corruption.
• Basically, pointer bugs are difficult to handle. So, use pointer effectively
and correctly.

By Prof. Radhika Shrimankar


Indirection Operator [*]
• The * operator is called the indirection operator because it allows you to
"indirectly" access the value where pointer points.
• We can also say that once the pointer variable points to an object, we can use the
indirection operator [*] to access what’s stored in the object.
• Not only to access but to modify or update, we can use the indirection operator.

Example :-
int a=5,*p;
p=&a;
printf(“\nValue of a is %d”,*p);
*p=40;
printf(“\nValue of a is %d”,*p);

By Prof. Radhika Shrimankar


Dereferencing a pointer.
• The term dereferencing operator is another way to describe the
same operation: accessing the value pointed to by a pointer.
• Dereferencing simply means following a pointer to the memory
location it points to and accessing the value there.
• you can also use the pointer to get the value of the variable, by
using the * operator (the dereference operator):
int x = 20;
int *ptr = &x; // Pointer to 'x'
int y = *ptr; // Dereferencing 'ptr' to get the value of 'x' (20)

By Prof. Radhika Shrimankar


Types of Pointer

1. Void pointer
2. Null pointer
3. Dangling pointer

By Prof. Radhika Shrimankar


void pointer/ Generic Pointer

• It is also known as generic pointer.


• It is a pointer that does not have any associated data type.
• These pointers can be used to point to the memory address of any
variable irrespective of their data type.
• But you have to do typecasting to get a value.

By Prof. Radhika Shrimankar


Why use a Void Pointer in C?

• The address that is assigned to any pointer must have the same data
type as we have specified in the declaration of the pointer.
• So, when we are declaring the float pointer, this float pointer won’t be
able to point to an int variable or any other variable.
• In simpler words, it will only be able to point to the float type variable.
We thus use a pointer to void to overcome this very problem.
• Void pointer is capable of pointing to any data type.
• One can assign the void pointer with any data type’s address, and then
assign the void pointer to any pointer without even performing some
sort of explicit typecasting.
• So, it reduces complications in a code.

By Prof. Radhika Shrimankar


Example
void main()
{
int a = 10;
float b = 3.14;
void *ptr;

ptr = &a; // Pointer holds address of 'a'


printf("Value of a: %d\n", *(int *)ptr); // Casting to int before dereferencing

ptr = &b; // Pointer now holds address of 'b'


printf("Value of b: %.2f\n", *(float *)ptr); // Casting to float before dereferencing

return 0;
}

By Prof. Radhika Shrimankar


Size of void pointer

• The size of a void pointer depends on the underlying


hardware architecture:
– 32-bit system: 4 bytes
– 64-bit system: 8 bytes
Limitations of using Void Pointers in C
– We cannot use it dereferenced.
– We cannot apply the arithmetic operations on void pointers in C
directly. We need to apply the proper typecasting so that we can
perform the arithmetic operations on the void pointers.

By Prof. Radhika Shrimankar


Null Pointer

• A null pointer is a pointer that does not point to any valid memory
location.
• It is initialized to NULL and used to indicate that the pointer is not
currently holding a valid address.
• Null means that the pointer is referring to the 0th memory
location.

By Prof. Radhika Shrimankar


Applications/Uses of Null Pointer

Application/Uses Example
Uninitialized pointer int *ptr = NULL;
End of data structure struct Node *next = NULL;
Error handling if (ptr == NULL) { ... }
Function argument default printMessage(NULL);
Dynamic memory deallocation free(ptr); ptr = NULL;
Recursive base case if (root == NULL) return;
Polymorphism placeholder (C++) Base *ptr = NULL;
Invalid return signal (e.g., fopen) if (file == NULL) { ... }

By Prof. Radhika Shrimankar


Null Pointer
#include <stdio.h>

int main()
{
int *ptr = NULL; // Null pointer

if (ptr == NULL) {
printf("Pointer is null, no valid memory address assigned.\n");
} else {
printf("Pointer is not null.\n");
}

return 0;
}

By Prof. Radhika Shrimankar


Dangling Pointer

• A dangling pointer in C refers to a pointer that does not point to a valid


object or memory location.
• This situation arises when the object that the pointer was pointing to
has been deallocated or freed, yet the pointer still holds the address of
that memory location.
• Accessing or dereferencing a dangling pointer can lead to undefined
behavior, crashes, or data corruption, making it a critical issue in
memory management.

By Prof. Radhika Shrimankar


Difference Ways of Pointer Act as a Dangling Pointer
1. De-allocation of memory
2. Function call
3. Variable is out of scope

int main()
{
int *ptr = (int *)malloc(sizeof(int)); // Dynamically allocated memory
*ptr = 42;

printf("Value before freeing: %d\n", *ptr);


free(ptr); // Memory is deallocated

// Dangling pointer: 'ptr' is not set to NULL after free


// printf("Value after freeing: %d\n", *ptr); // Undefined behavior

return 0;
}
By Prof. Radhika Shrimankar
Const Pointer

• A constant pointer in C cannot change the address of the variable to


which it is pointing, i.e., the address will remain constant.
• Therefore, we can say that if a constant pointer is pointing to some
variable, then it cannot point to any other variable.

By Prof. Radhika Shrimankar


Const pointer example
int main()
{
int a = 10, b = 20;
const int *ptr = &a; // Pointer to a constant int

printf("Value pointed by ptr: %d\n", *ptr);

// *ptr = 20; // Error: Cannot modify the value through the pointer
ptr = &b; // Allowed: Pointer can point to another address
printf("Value pointed by ptr: %d\n", *ptr);

return 0;
}
You cannot modify the value pointed to by ptr using the pointer.
You can change the pointer to point to another variable.
By Prof. Radhika Shrimankar
Const Pointer

Type Syntax Can Modify Address? Can Modify Value?


Pointer to Constant const int *ptr; Yes No
Constant Pointer int *const ptr = &a; No Yes
Constant Pointer to
const int *const ptr = &a; No No
Constant

By Prof. Radhika Shrimankar


Difference null and void Pointer
Aspect Void Pointer Null Pointer
A pointer that can point to any data A pointer that doesn't point to any
Definition type but doesn't have a specific valid memory location and is used
type itself. as a sentinel value.
Used to indicate that the pointer is
Used to store the address of any
Purpose not initialized or doesn't point to
variable, regardless of its data type.
any memory.
Cannot be dereferenced directly; Cannot be dereferenced because it
Dereferencing must be cast to a specific pointer doesn't point to a valid memory
type before dereferencing. location.
Points to a memory address of
Initialized with the value NULL to
Initialization some variable or function (after
indicate it points to nothing.
assignment).
Holds a valid memory address of Holds the value 0 or NULL, meaning
Memory Address
some variable or function. no valid memory address.
Example void *ptr; ptr = &x; int *ptr = NULL;
By Prof. Radhika Shrimankar
When we call different ways, then effect of it as follow.

By Prof. Radhika Shrimankar


Pass parameter as a variable in Function (Call by value)
• Function call by value is the default way of calling a function in C
programming.
• Different memory is allocated for actual and formal parameters.
• So the value of the actual parameter is copied into the formal
parameter.
• So any changes made inside functions are not reflected in actual
parameters of the caller.
• In short, we can not modify the value of the actual parameter by the
formal parameter in call by value.

By Prof. Radhika Shrimankar


Pass parameter as a variable in Function (Call by value)

By Prof. Radhika Shrimankar


Swapping of two number function. Call by value
#include <stdio.h>
void swap(int a,int b)
{ int c;
c=a; a==b; b=c;
printf(“After function call in main“);
printf(“\n\tFirst value is %d”,a);
printf(“\n\tSecond value is %d”,b); Output :-
} After function call
int main()
{
First value is 8
int a=5,b=8; Second value is 5
printf(“Before function call “); After function call in main
printf(“\n\tFirst value is %d”,a); First value is 5
printf(“\n\tSecond value is %d”,b); Second value is 8
swap(&a,&b);
printf(“After function call “);
printf(“\n\tFirst value is %d”,a);
printf(“\n\tSecond value is %d”,b);
return 0;
}

By Prof. Radhika Shrimankar


Pass parameter as a pointer in Function (Call by Reference)
• As an argument, a pointer is passed instead of a variable and its
address is passed instead of its value.
• As a result, any change made by the function using the pointer is
permanently stored at the address of the passed variable.
• This technique is known as call by reference in C.
• When we need this type of requirement then we use this concept.
• And also through this concept we can return more than one value at
a time.

By Prof. Radhika Shrimankar


Pass parameter as a pointer in Function (Call by Reference)
• In call by reference, the address of the variable is passed into the
function call as the actual parameter.
• As a result, any change made by the function using the pointer is
permanently stored at the address of the passed variable.
• The value of the actual parameters can be modified by changing the
formal parameters since the address of the actual parameters is passed.
• This technique is known as call by reference in C.
• In call by reference, the memory allocation is similar for both formal
parameters and actual parameters. All the operations in the function are
performed on the value stored at the address of the actual parameters,
and the modified value gets stored at the same address.

By Prof. Radhika Shrimankar


By Prof. Radhika Shrimankar
First Use :- To change the variable which passed by reference.

#include <stdio.h>
void salaryhike(int *sal)
{ *sal = *sal+2000;
Output :-
Salary before function is : 5000
} Salary after function call in main is : 7000

int main()
{
int salary=5000;
printf(“Salary before function is : %d", salary);
salaryhike(&salary);
printf(“Salary after function call in main is : %d", salary);
return 0;
By Prof. Radhika Shrimankar
Second Use :- To return more than one value without return statment

#include <stdio.h>
void swap(int *a,int *b)
{ int c;
c=*a; *a=*b; *b=c;
}
int main() Output :-
{ Before function call in main
int a=5,b=8; First value is 5
printf(“Before function call in main “); Second value is 8
printf(“\nFirst value is %d”,a); After function call in main
printf(“\nSecond value is %d”,b); First value is 8
Second value is 5
swap(&a,&b);
printf(“After function call in main“);
printf(“\nFirst value is %d”,a);
printf(“\nSecond value is %d”,b);
return 0;
}

By Prof. Radhika Shrimankar


Srno
Call by Value Call by Reference
.

In this method, it passes the value of the In this method, it passes the address of the
1
variable as an argument. variable as an argument.

In this method, the actual value is not In this method, the actual value is
2
modified. modified.

3 This method is slow. This method is fast.

Both formal and actual parameters have Both formal and actual arguments are at
4
different memory locations. the same memory location.

Syntax :-
Syntax :-
Return type funname(dttype
5 Return type funname(dttype var1,dttype
*ptrvar1,dttype *ptrvar2,…)
var2,…) By Prof. Radhika Shrimankar
Return pointer from function
• We can also return pointer from a function.
• When pointer is returned from a function, it must point to data in
the calling function or global variable.
Syntax :

return type *function name(pointer variable arguments)

By Prof. Radhika Shrimankar


Program : - Find maximum number among two numbers
using return pointer from function concept
int *max(int *a,int *b);
void main()
{
int a=8,b=20,*ans;
ans=max(&a,&b);
printf(“\nMax no is %d”,*ans);
}
int *max(int *a,int *b)
{
if(*a > *b)
return *a;
else
return *b;
}
By Prof. Radhika Shrimankar
Array and pointer
• The name or identifier of an array is itself a constant pointer to
the array.
• Its value is the address of the first element of the array.
• One dimensional Arrays and Pointers-Elements of array are
stored in the successive increasing locations of memory.

By Prof. Radhika Shrimankar


Relationship between array and pointer
• In C-language pointer and array are very close to each other,
an array can be split in the form of the pointer.
• The name of the array is a pointer to its first element.
• Example :- int marks[10]
– Here marks defines the address of its first element.
– &marks[0] also defines the address of its first element.

By Prof. Radhika Shrimankar


Relationship between array and pointer
• marks [i] = *(marks +i) 1D array in form of pointer
• a[i] = *(a+ i) ith element of an 1D array
• marks [i][j] = *(marks [i]+j); 2D array in form of 1D array and
pointer.
• marks [i][j] = *(*(marks + i) + j) 2D array in form of pointer.

By Prof. Radhika Shrimankar


How can we fetch address of an array :-
int a[10];
First way :-
– Mentioning the name of the array fetches its base address.
– Example :- printf(“Address of array is %u”,a);
Second way :-
– Mentioning the base address of first element of array.
– Example :- printf(“Address of array is %u”,&a[0]);
Note
– The name of an array is a constant pointer to the array and cannot be
incremented or decremented.

By Prof. Radhika Shrimankar


Address of an array

#include <stdio.h>
int main()
{
int array[]={10, 20, 30, 40, 50};
printf(“%u \t %u”, array, &array[0]);
return 0;
}
Output:
2147478270 2147478270
By Prof. Radhika Shrimankar
Pointer to Array
Declaration of pointer to array
data_type *pointer_variable, array_variable[size];
Initialization of pointer to array
pointer_variable=&array_variable[0];
OR
pointer_variable=array_variable;
Example :-
int a[5],*p;
Initialize pointer with the base address of array
p=a; // p=&a[0];
By Prof. Radhika Shrimankar
Pointer Notation

By Prof. Radhika Shrimankar


Print Array data without pointer notation.
#include <stdio.h>
#include <stdio.h>
int main()
int main()
{ {
int a[]={10, 20, 30, 40, 50}; int a[]={10, 20, 30, 40, 50};
int i; int i;
for(i=0;i<5;++i) for(i=0;i<5;++i)
printf(“\n%d”, a[i]); printf(“\n%d”, *(a+i));
return 0; return 0;
} }
Output: Output:
10 10
20 20
30 30
40 40
50 50

By Prof. Radhika Shrimankar


Array and Pointers Basics-
#include <stdio.h>
int main() Output:
{ 10
int a[]={10, 20, 30, 40, 50}; 20
int i, *p; 30
p=a; /* it can also be written as p=&a[0]; */ 40
for(i=0;i<5;++i) 50
printf(“\n%d”, p[i]);
return 0; Different ways to access data
printf (“\n%d”, *(p+i));
} printf (“\n%d”, *(i+p));
printf (“\n%d”, i[p]);
By Prof. Radhika Shrimankar
Difference between Array name and Pointer
Array Name Pointer
When memory is allocated for the array, the Instead, if necessary, separate pointer variables of
starting address is fixed, i.e., it cannot be changed the appropriate type may be declared and used as
during (address constant) program execution. lvalues.

An array cannot be assigned to another array Not true in case of pointers


because an array name cannot be used as lvalue.

The sizeof operator returns the size of the allocated In case of a pointer, the sizeof operator returns two
space for arrays. or four or more bytes of storage (machine
dependent).

By Prof. Radhika Shrimankar


Difference between Array and Pointer
Array Pointer
Arrays are used to store multiple values in a The pointer is a special type of variable, which
single variable, instead of declaring separate points (stores) address of another variable.
variables for each value.
Array is a constant pointer. Pointer variable can be changed.
It refers directly to the elements. It refers address of the variable.
Memory allocation is in sequence. Memory allocation is random.
Allocates the memory space which cannot
Allocated memory size can be resized.
resize or reassigned.
It is not a group of elements. It is a single
It is a group of elements.
variable.
Array can be initialized at definition.
Pointer can’t be initialized at a definition
Example :- int num[] = { 2, 4, 5}

By Prof. Radhika Shrimankar


Passing 1-D array using Pointer to Function
• There are mainly 3 following ways to pass an array to a
function in C.
1. Formal parameter as pointers
2. Formal parameter as a sized array
3. Formal parameter as unsized array

By Prof. Radhika Shrimankar


Formal parameter as pointers
• In this approach, the function call accepts an address of an
array and accesses it using pointer as an argument to the
function call.
Syntax :-
return_type functionName(type * array_name)
{
// Function Definition
}

By Prof. Radhika Shrimankar


Formal parameter as pointers
void sort(int *a)
void sort(int *a); {
int main()
{ int i,j,temp;
int a[10],i; for(i=0;i<5;i++)
for(i=0;i<5;i++) {
{ for(j=i+1;j<5;j++)
printf("\nEnter number"); {
scanf("%d",&a[i]); if(a[i]>a[j])
} {
printf("\n\n"); temp=*(a+i);
sort(a);
*(a+i)=*(a+j);
for(i=0;i<5;i++)
{ *(a+j)=temp;
printf("\t%d",a[i]);
} }
}
return 0; }
} }
By Prof. Radhika Shrimankar
Formal parameter as a sized array
• In this approach, the function call accepts an address of an
array and accesses it using a pointer with a subscript
notation [ array_size ] as an argument to a function call.
Syntax :-
return_type functionName(type array_name[size])
{
// Function Definition
}

By Prof. Radhika Shrimankar


Formal parameter as unsized array
• In this approach, the function call accepts the address of the
array and accesses it using a pointer with a blank subscript
notation [ ] as an argument to a function call. It is the most
widely used method while working with arrays.
Syntax :-
return_type functionName(type array_name[])
{
// Function Definition
}

By Prof. Radhika Shrimankar


void sort(int a[]);
void sort(int a[])
int main()
{
{
int a[10],i; int i,j,temp;
for(i=0;i<5;i++) for(i=0;i<5;i++)
{ {
printf("\nEnter number"); for(j=i+1;j<5;j++)
scanf("%d",&a[i]); {
} if(a[i]>a[j])
printf("\n\n");
{
sort(a);
for(i=0;i<5;i++)
temp=a[i];
{ a[i]=a[j];
printf("\t%d",a[i]); a[j]=temp;
}
}
return 0; }
} }
} By Prof. Radhika Shrimankar
Passing 2-D array using Pointer to Function
• There are mainly 4 following ways to pass an array to a function in
C.
1. Formal parameter as both dimensions are available globally
2. Formal parameter as only second dimension is available globally
3. Formal parameter as a single pointer
4. Formal parameter as pointer to an array

By Prof. Radhika Shrimankar


Formal parameter as a single pointer
• In C language, the compiler calculates offset to access the
element of the array.
• The calculation of the offset depends on the array
dimensions.

By Prof. Radhika Shrimankar


Access a 2-D array using a single pointer

General expression to calculates offset for 2D array is that,


(ithRow * Total_number_Coloumb)+ jthColoumb).
To Access a[i][j] = *(a[i]+ j) = (*(a + i))[j] = *(*(a + i) + j)

By Prof. Radhika Shrimankar


Access a 2-D array using a single pointer
void print(int *arr, int m, int n)
{
int i, j;
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
printf("%d ", *((arr+i*n) + j));
}

int main()
{
int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int m = 3, n = 3;

// We can also use "print(&arr[0][0], m, n);"


print((int *)arr, m, n);
return 0;
} By Prof. Radhika Shrimankar
Function Pointer
• As we know that we can create a pointer of any data type
such as int, char, float, we can also create a pointer pointing
to a function.
• The code of a function always resides in memory, which
means that the function has some address.
• We can get the address of memory by using the function
pointer.
• Like every variables function also has unique memory
address.

By Prof. Radhika Shrimankar


Function Pointer
Syntax :- void (*fptr)();
– We must enclose the function pointer variable with (). like (*fptr).
– If we want to point a function whose return type is int and it takes
one integer argument i.e. int fun(int); then the declaration will be,
int (*fptr)(int);

By Prof. Radhika Shrimankar


Declaration of a function pointer

float (*fp) (int , int); // Declaration of a function pointer.


float func( int , int ); // Declaration of function.
fp = func; // Assigning address of func to the fp pointer.

• In the above declaration, 'fp' pointer contains the address of


the 'func' function.
• Declaration of a function is necessary before assigning the
address of a function to the function pointer.
Calling a function through a function pointer
result = (*fp)( a , b); OR result = fp(a , b);

By Prof. Radhika Shrimankar


Function Pointer
void hello()
{
printf("Hello\n");
}

int main()
{
//function name itself holds the memory address of a function
printf("Address of function hello = %p\n",hello);

return 0;
}

By Prof. Radhika Shrimankar


Function Pointer

void hello()
{
printf("Hello\n");
}

int main()
{
void (*fptr)();

fptr = hello; //fptr references function hello

(*fptr)(); //dereferencing function pointer

return 0;
}

By Prof. Radhika Shrimankar


Pointer with String

• Strings are character arrays terminated by null character.


• Pointer to a single string may be declared in the same way as
the pointer to a one-dimensional array.
• Example :-
char Name[] = “Dinesh”;
char *ptrname ;
ptrname = Name;
By Prof. Radhika Shrimankar
Pointer with String

• Though the declaration and initialization of a pointer to a


string is similar to that of a pointer to an array, the difference
lies in the input/output.
• String may be taken as a single object for input and output
and its characters may also be treated like elements of an
array.

By Prof. Radhika Shrimankar


Print one by one character with Pointer
int main()
{
char s1[10],*p1; • p1 - is a character pointer which
p1 = s1; points the first character of the
printf("\nEnter String 1:");
string. i.e. &s1[0]
gets(s1); • Like normal pointer arithmetic, if we
while(*p1!='\0') move the p1 by 1 (p1+1) position it
{ will point the next character.
printf("%c",*p1);
p1++;

}
return 0;
By Prof. Radhika Shrimankar
To copy character array to the character array using
pointer.
int main()
{
char s1[10],s2[10],*p1,*p2;
p1 = s1; • p1 - is a character pointer which
p2 = s2;
printf("\nEnter String 1:");
points the first character of the
gets(s1); string. i.e. &s1[0]
while(*p1!='\0')
{
• Like normal pointer arithmetic, if we
*p2 = * p1; move the p1 by 1 (p1+1) position it
p1++;
p2++; will point the next character.
}
*p2 = '\0';
printf("\nString 2 is:");
puts(s2);
return 0;
}
By Prof. Radhika Shrimankar
To concat two Strings using Pointer.
#include <stdio.h> while(*p1!='\0')
int main() {
*p3 = *p1;
{ p3++;
char str1[10],str2[10],str3[10],*p1,*p2,*p3; p1++;
p1 = str1; }
p2 = str2; while(*p2!='\0')
{
p3 = str3; *p3 = *p2;
printf("Enter String 1:"); p3++;
gets(str1); p2++;
}
printf("\nEnter String2:");
*p3 = '\0';
gets(str2); printf("\nCombine string is:");
puts(str3);
getch();
}
By Prof. Radhika Shrimankar
Output-

By Prof. Radhika Shrimankar


To count characters, words and lines in given
string using pointer.
if(*pstr == ' ' && *(pstr+1)!=' ')
void main() {
{ words++;
char str[100],*pstr; }
int chars = 1,lines = 1,words = 1;
chars++;
pstr = str;
pstr++;
printf("Enter the String:");
}
gets(str);
printf("\nThe String is:");
while(*pstr != '\0')
puts(str);
{
if(*pstr !== '\n')
printf("\nThe number of characters:%d",chars);
{ printf("\nThe number of lines:%d",lines);
lines++; printf("\nThe number of words:%d",words);
} getch();
} By Prof. Radhika Shrimankar
Output-
Enter the String: How are you
The String is: How are you
The number of characters:11
The number of lines:1
The number of words:3

By Prof. Radhika Shrimankar


Read string and count the number of uppercase and
lowercase characters entered using pointer
void main() else if(*pstr>= 'a' && *pstr<='z')
{ {
char str[100],*pstr; lower++;
int upper=0,lower=0; }
printf("\nEnter the String:"); pstr++;
gets(str); }
pstr = str; printf("\nThe total number of uppercase
while(*pstr != '\0) characters:%d",upper);
{ printf("\nThe total number of lowercase
if(*pstr>= 'A' && *pstr<='Z') characters:%d",lower);
{ upper++; } getch();
} By Prof. Radhika Shrimankar
Output-

By Prof. Radhika Shrimankar


Static Memory Allocation

• Static Memory Allocation, also known as Compile-time Memory


Allocation, is used for the allocation of memory during the process of
compilation of data in a fixed size.
• The compiler allocates memory for variables present in the program.
• The size of data required for the program execution is mentioned
beforehand, before the initiation of the execution.
• Small size leads to inappropriate execution and large size leads to
wastage.
• This method leads to memory wastage.
• If memory is not required, it cannot be freed. It remains unchanged
permanently

By Prof. Radhika Shrimankar


Dynamic Memory Allocation

• Dynamic Memory Allocation, also known as Run-time


Memory Allocation, is used for the allocation of memory
during the process of execution (Runtime) of data.
• It allows allocation to entities when the program is running
for the first time.
• It allocates exact space and size for the Dynamic content and
hence allocation is done during the runtime which decreases
the wastage of space.

By Prof. Radhika Shrimankar


Properties of Dynamic Memory Allocation
• Value is assigned to a pointer variable which is returned by
different functions.
• Memory is allocated during execution.
• Memory can be allocated at any time and released at any time.
• Heap memory is used here.
• Dynamic memory allocation is slow but more efficient.
• Implementation of the program is complicated.
• Memory can be resized dynamically or reused.
• It is used in linked lists.

By Prof. Radhika Shrimankar


Advantages of Dynamic Memory Allocation
• It allows the allocation of memory at runtime.
• The memory size of data structures can be increased or
decreased based on the requirements of the dynamic memory
allocation.
• Memory wastage doesn't occur because it allocates exact
memory space to the program to enhance the performance of
the system.

By Prof. Radhika Shrimankar


Disadvantages of Dynamic Memory Allocation
• It requires more execution time due to execution during
runtime.
• Once the program is executed, it needs to be freed or bugs
are formed which are difficult to find.

By Prof. Radhika Shrimankar


Sr. No Static Memory Allocation Dynamic Memory Allocation
1 When the allocation of memory performs at When the memory allocation is done at the
the compile time, then it is known as static execution or run time, it is called dynamic memory
memory. allocation.
2 The memory is allocated at the compile The memory is allocated at the runtime.
time.
3 In static memory allocation, the memory In dynamic memory allocation, while executing a
cannot be changed while executing a program, the memory can be changed.
program.
4 Static memory allocation is preferred in an Dynamic memory allocation is preferred in the
array. linked list. By Prof. Radhika Shrimankar
5 It saves running time as it is fast. It is slower than static memory allocation.
6 Static memory allocation allots memory Dynamic memory allocation allots memory from
from the stack. the heap.
7 Once the memory is allotted, it will remain Here, the memory can be alloted at any time in the
from the beginning to end of the program. program.
8 Static memory allocation is less efficient as Dynamic memory allocation is more efficient as
Function Task
ng
malloc() Allocates memory and returns a pointer to the first byte
of allocated space
calloc() Allocates space for an array of elements and initialize
them to zero.
Like malloc(), calloc() also returns a pointer to the
memory.
free() Frees previously allocated memory
realloc() Alters the size of previously allocated memory

By Prof. Radhika Shrimankar


Malloc function
• Using malloc function, we can create memory dynamically at
runtime.
• malloc is declared in <stdlib.h> i.e. standard library header
file.
• To use malloc function in our program, we have to include
<stdlib.h> header file.
Syntax :- malloc(size in bytes);

By Prof. Radhika Shrimankar


char *ptr;
ptr = malloc(10);
malloc will take only one argument.

where,

ptr is a pointer. It can be any type.

malloc - used to create dynamic memory

10 - It will allocate 10 bytes of memory.

By Prof. Radhika Shrimankar


How does malloc work?

• malloc will create the dynamic memory with given size


and returns the base address to the pointer.
• If malloc unable to create the dynamic memory, it will
return NULL.
• So, it is mandatory to check the pointer before using it.
//allocating memory for 5 integers using malloc
– int *ptr = malloc(5*sizeof(int));

By Prof. Radhika Shrimankar


Initialization

• malloc doesn't initialize the memory area which is created


dynamically.
• So, the memory area will have garbage values.

By Prof. Radhika Shrimankar


#include<stdio.h>
//To use malloc function in our program
#include<stdlib.h>

int main()
{
int *ptr,size,i;

scanf("%d",&size);

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

if(ptr != NULL)
{
//let's get input from user and print it
printf("Enter numbers\n");

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


scanf("%d",ptr+i);

//printing values
printf("The numbers are\n");

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


printf("%d\n",*(ptr+i)); // *(ptr+i) is as same as ptr[i]

} By Prof. Radhika Shrimankar


Calloc function

• Using calloc function, we can create memory dynamically at


runtime.
• calloc is declared in <stdlib.h> i.e. standard library header
file.
• To use calloc function in our program, we have to include
<stdlib.h> header file.
Syntax :- calloc(number of elements, size of the element);

By Prof. Radhika Shrimankar


int *ptr;
ptr = calloc(n,size);

calloc will take two arguments.


where,
ptr is a pointer. It can be any type.
calloc - used to create dynamic memory
n - number of elements
size- size of the elements

By Prof. Radhika Shrimankar


How does calloc work?

• It will return the base address of an allocated memory to the


pointer variable, on success.
• If calloc unable to create the dynamic memory, it will
return NULL.
• So, it is mandatory to check the pointer before using it.
//allocating memory for 5 integers using calloc

int *ptr = calloc(5,sizeof(int));

By Prof. Radhika Shrimankar


Initialization
• calloc will initialize the memory to zero.
• So, the allocated memory area will be set to 0.

By Prof. Radhika Shrimankar


int main()
{
int *ptr,n,i;

scanf("%d",&n);

ptr = calloc(n,sizeof(int));

if(ptr != NULL)
{
//let's get input from user and print it
printf("Enter numbers\n");

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


scanf("%d",ptr+i);

//printing values
printf("The numbers are\n");

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


printf("%d\n",*(ptr+i)); // *(ptr+i) is as same as ptr[i]

return 0;
}

By Prof. Radhika Shrimankar


Difference between malloc and calloc
The name malloc stands for memory allocation. The name calloc stands for contiguous
allocation.
malloc() function creates a single block of calloc() function assigns multiple blocks of
memory of a specific size. memory to a single variable.

malloc(size in bytes); calloc(number of elements, size of the


element);
The number of arguments in malloc() is 1. The number of arguments in calloc() is 2.

malloc() is faster. By Prof. Radhika Shrimankar calloc() is slower.

malloc() has high time efficiency. calloc() has low time efficiency.

The memory block allocated by malloc() has a The memory block allocated by calloc() is
garbage value. initialized by zero.
Relloc - To alter the size of allocated memory

• At times the memory allocated by using calloc() or malloc()


might be insufficient or in excess.
• In both the situations we can always use realloc() to change
the memory size already allocated by calloc() or malloc().
• The process is called reallocation of memory.
Syntax :-
– ptr= realloc(ptr,newsize)

By Prof. Radhika Shrimankar


#include <stdio.h>
#include <stdlib.h>
void main()
{
int N,*a,i;
printf(“\n enter no. of elements of the array:”);
scanf(“%d”,&N);
a=(int *)malloc(N*sizeof(int));
if(a==NULL)
{
printf(“\n memory allocation unsuccessful...”);
exit(0);
}
// After some of the statements we need relocate then we do like below.

printf(“enter new size of an array);


scanf(“%d”,&N);
a=(int *)realloc(a,N*sizeof(int))
if(a==NULL)
{
printf(“\n memory allocation unsuccessful...”);
exit(0);
}
}
By Prof. Radhika Shrimankar
Free memory -
• It's mandatory to deallocate the memory area which has created
dynamically when the memory is no longer needed.
• When we try to create the dynamic memory, the memory will be
created in the heap section.
• If we don't deallocate the dynamic memory, it will reside in the
heap section.It is also called memory leak.
• It will reduce the system performance by reducing the amount of
available memory.
Syntax :- free(ptr);
By Prof. Radhika Shrimankar
Void pointer -
• A void pointer is a special type of pointer. It can point to any data
type, from an integer value or a float to a string of characters.
• A void pointer can hold address of any type and can be typcasted
to any type.
• Therefore, type casting or assignment must be used to turn the
void pointer to a pointer of a concrete data type to which we want
to refer.

By Prof. Radhika Shrimankar


Example of void pointer
#include <stdio.h>
int main()
Output:
{ a= 5
int a=5, b= 3.141500
double b=3.1415;
void *vp;
vp=&a;
printf(“\n a= %d”, *((int *)vp));
vp=&b;
printf(“\n b= %f”, *((double *)vp));
return 0;
}
By Prof. Radhika Shrimankar
NULL pointer -
• NULL pointer is a pointer which points nothing.
• A null pointer is a special pointer that points nowhere.
• That is, no other valid pointer to any other variable or array cell or
anything else will ever be equal to a null pointer.
• The most straightforward way to get a null pointer in the program
is by using the predefined constant NULL.
• If we do not have any address which is to be assigned to the
pointer, then it is known as a null pointer. When a NULL value is
assigned to the pointer, then it is considered as a Null pointer.
By Prof. Radhika Shrimankar
Null pointer
• If it is too early in the code to know which address to assign to the
pointer, then the pointer can be assigned to NULL, which is a
constant with a value of zero defined in several standard libraries,
including stdio.h.

By Prof. Radhika Shrimankar


Example Null pointer
#include <stdio.h>
int main()
{
int *p;
p = NULL;
printf(“\n The value of p is %u”, p);
return 0;
}
Output:
The value of p is 0 By Prof. Radhika Shrimankar
Memory corruption -
• Memory corruption often occurs when due to programming
errors, the content of a memory location gets modified
unintentionally.
• When program uses the contents of the corrupted memory, it
either results in program crash or in storage.

By Prof. Radhika Shrimankar


Pointer to constant -
• As the name itself indicates, the value of the variable to which the
pointer is pointing, is constant.
• In other words, a pointer through which one cannot change the
value of the variable to which it points is known as a pointer to
constant.
• Note: These pointers can change the address they point to but
cannot change the value at the address they are pointing to.

By Prof. Radhika Shrimankar


Example of pointer to constant
int main()
{
int a = 10;
int b = 20;
const int* ptr = &a;

//Now, ptr is pointing to the value of the variable

ptr = &b; // Works: Since pointer is not constant


*ptr = 30; //Error: Since the value is constant
}
By Prof. Radhika Shrimankar

You might also like