pointer
pointer
89
OVERVIEW
• Introduction
• Pointer declaration
• Pointer arithmetic
• Pointer and array
90
Pointers
• A pointer is a special variable in C programming language which stores the memory address of other
variables of the same data type. As a pointer is variable, it is also created in some memory location.
Declaration of Pointer Variable
data_type * pointer_name;
Here, data_type can be any valid C data types and pointer_name can be any valid C identifier.
Examples of Declaration of Pointer:
int *ptr;
Here ptr is a pointer variable and it is read as a pointer to integer since it can point to integer variables.
float *fptr;
Here fptr is a pointer variable and it is read as a pointer to float since it can point to float variables.
char *cp;
Here cp is a pointer variable and it is read as a pointer to character since it can point to character variables.
91
Referencing of Pointer (Initialization of Pointer):
• Making a pointer variable to point other variables by providing address of that variable to the pointer is known as
referencing of pointer.
• It is also known as initialization of pointers. For proper use of pointer, pointer variables must point to some valid
address and it is important to note that without referencing, pointer variables are meaningless.
General syntax for referencing of pointer is:
pointer_variable = &normal_variable;
Here pointer_variable and normal_variable must be of the same data types.
Examples of Referencing of Pointer:
int a=10;
int *ptr; a variable
ptr = &a; 10 value
Here pointer ptr got address of variable a 0x2000 address
so, pointer ptr is now pointing to variable a. ptr Pointer variable
0x2000 value
ox3000 address
92
Contd…
int *ptr = #
93
float val=5.5;
float *p;
p = &val;
Here pointer p got address of variable val so, pointer p is now pointing to
variable val.
But!!!
float x=30.4;
int *iptr;
iptr = &x;
is invalid!!! Because pointer iptr cannot store address of float variable.
94
Dereferencing of Pointer (*)
• The operator * (asterisk) used in front of the name of the pointer variable is known as pointer or
dereferencing or indirection operator.
• After valid referencing of pointer variable, * pointer_variable gives the value of the variable pointed by
pointer variable and this is known as dereferencing of pointer.
• Simply, *pointer_variable after referencing instructs compilers that go to the memory address stored by
pointer_variable and get value from that memory address.
Operators:
& address of
* Value at address
95
Example
#include <stdio.h>
int main(void);
int main(void)
{
int num = 10;
int *ptr = #
printf("Value of num = %d", num);
printf("\n\rAddress = %p", &num);
printf("\n\rPointer ptr = %p", ptr);
printf("\n\rValue pointer is pointing at = %d", *ptr);
return 0;
}
96
Uses of Pointer
1. Dynamic Memory Allocation: Allocate memory at runtime using malloc(), calloc(), and
free().
2. Passing by Reference: Pass the address of a variable to a function, allowing modification
of the original value.
3. Array Manipulation: Pointers enable efficient access to array elements and traversal
through arrays.
4. Pointer to Functions: Store function addresses to allow dynamic function calls (e.g.,
callbacks).
5. Linked Data Structures: Used in creating and manipulating linked lists, trees, and other
dynamic structures.
6. Structures: Pointers enable dynamic memory allocation for structures and access their
members.
7. Efficient Data Handling: Pointers allow passing large data (arrays/structures) without
copying them, improving efficiency.
97
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x=10,y;
int *p;
p=&x;
y=*p;
printf("value of x:%d\n",x);
printf("%d is stored at %d\n",x,&x);
printf("%d is stored at %d\n",*&x,&x);
printf("%d is stored at %d\n",*p,p);
printf("%d is stored at %d\n",p,&p);
printf("%d is stored at %d\n",y,&y);
*p=50;
printf("\nNow value at x:%d",x);
return 0;
}
98
limitations of pointers:
[Link] Leaks: Failing to release memory that is no longer needed, which can cause the program to use
too much memory.
[Link] Pointers: Using a pointer after the memory it points to has been freed, which can cause errors or
crashes.
[Link] Pointer Dereferencing: Trying to access memory through a pointer that has not been initialized (i.e.,
points to NULL), leading to a crash.
[Link] Arithmetic Errors: Incorrectly modifying pointers can lead to accessing invalid memory
locations, causing unpredictable behavior.
[Link] to Debug: Errors related to pointers can be hard to identify and fix, making debugging more
challenging.
[Link] Safety Issues: Pointers can be incorrectly cast to different types, leading to memory corruption.
[Link] Faults: Accessing invalid or uninitialized memory locations can cause the program to crash.
[Link] Dependence: Pointers behave differently on different computer architectures (32-bit vs 64-bit),
which can cause portability issues.
[Link] Pointers: Using pointers that are not set to a valid memory address can result in random and
unexpected behavior.
[Link] Risks: Improper use of pointers can create security vulnerabilities, such as buffer overflows,
which attackers can exploit.s
99
Reference(&) and deference(*) operator
Reference operators:
• Address of operator (“&”) is known as referencing operator.
• This operator returns the address of the variable associated with the operator.
• For e.g., if we write “&x”, it will return the address of the variable “x’.
• Hence, if we have a pointer “p”, which we want to point to a variable x, then we need to copy the
address of the variable “x” in the pointer variable “p”.
• This is implemented by the statement: p = &x;
Dereference operators:
• Value of operator (“*”) is known as dereference operator.
• This operator returns the value stored in the variable pointed by the specified pointer.
• For e.g., if we write “*p”, it will return the value of the variable pointed by the pointer “p”.
• Hence, if we want the value of the variable pointed by the pointer “p” to be stored in a variable “y”, then
the expression can be written as: y = *p;
100
Bad Pointer
• When a pointer is first allocated, it does not have a pointee. The pointer is "uninitialized" or simply
"bad". A dereference operation on a bad pointer is a serious runtime error.
• Each pointer must be assigned a pointee before it can support dereference operations. Before that, the
pointer is bad and must not be used.
• In fact, every pointer starts out with a bad value. Correct code overwrites the bad value with a correct
reference to a pointee, and thereafter the pointer works fine.
Example:
int* p; // allocate the pointer, but not the pointee
*p = 42; // this dereference is a serious runtime error
Correct code:
int x=42,*p;
p=&x;
101
void pointer
• A void pointer is a special type of pointer . It can point to any data type, from an
integer value to a float and a string of characters.
• Using void pointer, the pointed data can not be referenced directly( i.e,
*(asterisk) operator cannot be used on them.)
• Type casting or assignment must be used to change the void pointer to a
concrete data type to which we can refer.
• Void pointer is highly preferred in dynamic memory allocation using malloc() and
calloc().
• A void pointer is a most convention way in c for storing a raw address.
102
Sample code
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a=10;
float b=4.56;
char *ch="NEPAL";
void *vptr;
vptr=&a;
printf("value=%d\n",*(int *)vptr);
vptr=&b;
printf("value=%f\n",*(float *)vptr);
vptr=&ch;
printf("value=%s\n",*(char **)vptr);
return 0;
}
103
NULL pointer
• C program defines the states that for each pointer type, when a pointer variable is
declared and initialized either by a Null value or by 0 explicitly then the pointer
variable is said to be null pointer.
• Conceptually a null pointer is a pointer that points nowhere, it doesn't have an
address of any function or a variable , instead pointer is initialized
with zero or null to indicate that this pointer variable is still unused.
104
What will be the output of following?
#include<stdio.h>
int main() {
if(! NULL)
printf("C programming is easy");
else
printf("C programming is not easy");
return 0;
}
105
Pointer to Pointer(Double Pointer)
• A pointer variable
containing the address of Example: A=5
another pointer variable is B=10
known as pointer to pointer ptr= &A
or a chain of pointers. The
pointer variable that holds dptr= &ptr
the address of another
variable should be declared A 5 223344
with additional asterisk (*).
B 10 443322
ptr 223344 556688
dptr 556688 112234
106
#include <stdio.h>
int main()
{
int i = 5;
int *ptr1, **ptr2;
ptr1 = &i;
ptr2 = &ptr1;
printf("The value of i = %d ", i);
printf("\nThe value of ptr1 = %d ", *ptr1);
printf("\nThe value of ptr2 = %d ", **ptr2);
printf(“\n The address of i=%d”,&i);
printf(“\n The value assigned to ptr1=%d and value at address=%d”,ptr1,*ptr1);
printf(“\n The value assigned to ptr2=%d and single indirection value=%d and double indirection
value=%d”,ptr2,*ptr2,**ptr2);
return 0;
}
107
Pointer Arithmetic( Pointer Operations)
• Performing arithmetic operations on pointers is different from performing them on
regular integer data types.
• let us consider following declaration of ordinary variables and pointer variables.
int a,b;
Float c;
int *p1,*p2;
float *f;
1) A pointer variable can be assigned the address of an ordinary variable.
i.e, p1=&a; p2=&b; f=&c;
2) Content of one pointer can be assigned to other pointer provided they point to
same data type.
p1=p2; // valid!!
f=p1; //invalid!!
108
3) Integer data can be added to or subtracted from pointer variables.
Eg: p1+2; // specifies an address which is two memory blocks for integer data
beyond the address pointed by p1;
Pointer variable
p1 p1+1 p1+2
Similiarly, f+1;// specifies an address which is one memory block for folat data
beyond the address pointed by f.
Pointer variable
f f+1 f+2
109
4) One pointer can be subtracted from other pointer provided they point to the
elements of same array. For example:
int main()
{
int a[]={45,89,90,20}, *pf,*pl;
pf=a;
pl=a+2;
printf(“%d\n”,pl-pf);
printf(“%d”,*pf-*pl);
OUTPUT: 2
-45
5) Two pointer variables can be compared provided both pointers point to objects of
same data type.
if(p1<p2)
{
……..
………
} // is a valid comparision
110
6) There is no meaning in assigning an integer to a pointer variable.
p1=100; //It has no meaning.
p2=65560;
7) Two pointer variables can not be multiplied and added together.
p1+p2; // invalid!!
p1*p2; // invalid!!
8) A pointer variable cannot be multiplied by a constant.
p1*2; //invalid!!
9) NULL value can be assigned to a pointer variable.
p1=NULL; // Valid!!
111
What will be the output of following
problem?
#include<stdio.h>
void main()
10 65510 65550
{
int a=10, *b, **c;
a b
b=&a; 65550 c
65510
c=&b; 65580
printf("%d\t%d\t%d\n", &a,&b,&c);
printf("%d\t%d\n", b,*c);
printf("%d\t%d\n", c,**c);
printf("%d\t%d",*b+5, &c+2); Output
65510 65550 65580
} 65510 65510
65550 10
15 65588
112
Array of Pointers
• Since a pointer variable always contains an address, an array of pointer would be nothing but a collection of address.
• The address present in the array of pointers can be address of isolated variables or address of array elements.
Example:
int main()
{
int *arr[3];
int i=30,j=20,k=40,m;
arr[0]=&i;
arr[1]=&j;
arr[2]=&k;
for(m=0;m<3;m++)
{
printf(“%d\t”,*arr[m]);
}
return 0;
}
113
Returning Multiple Values Using Pointers in C
In C, functions can only return a single value. However, there are cases where
a function needs to return multiple values. C allows this by using pointers.
By passing the addresses (or references) of variables to the function, the
function can modify the values of those variables in the calling [Link]
allows us to simulate returning multiple values from a function.
To return multiple values using pointers, follow this structure:
1. Declare pointer parameters in the function.
2. Pass the addresses of the variables to the function.
3. Dereference the pointers inside the function to modify the values.
114
Example :Write a C function that takes two integers
as input and returns their sum and product using
int main() {
pointers. Display the results in the main function.
int num1, num2;
#include <stdio.h>
int sum, product;
void calculate(int a, int b, int *sum, int *product)
printf("Enter first number: ");
{
scanf("%d", &num1);
*sum = a + b; // Modify the sum at the address
pointed by 'sum' printf("Enter second number: ");
*product = a * b; // Modify the product at the scanf("%d", &num2);
address pointed by 'product' calculate(num1, num2, &sum, &product);
} printf("Sum: %d\n", sum);
printf("Product: %d\n", product);
return 0;
}
115
Array and Pointers
116
Alternative Representation: Example
#include <stdio.h>
int main() {
int x[5] = {1, 2, 3, 4, 5};
int* ptr;
// ptr is assigned the address of the third element
Output:
ptr = &x[2]; *ptr = 3
printf("*ptr = %d \n", *ptr); *(ptr+1) = 4
*(ptr-1) = 2
printf("*(ptr+1) = %d \n", *(ptr+1));
printf("*(ptr-1) = %d", *(ptr-1));
return 0;
}
117
WAP input 5 numbers and display their sum.
// Pointer representation of One dimensional Array
// One dimensional Array #include <stdio.h>
#include <stdio.h> #include <stdlib.h>
#include <stdlib.h> int main()
int main() {
{ int *num,i,sum=0;
int num[5],i,sum=0; printf("Enter 5 numbers");
printf("Enter 5 numbers"); for(i=0;i<5;i++)
for(i=0;i<5;i++) {
{ scanf("%d",(num+i));
scanf("%d",&num[i]); }
} // calculation
// calculation for(i=0;i<5;i++)
for(i=0;i<5;i++) {
{ sum=sum+ *(num+i);
sum=sum+num[i]; }
} printf("\nSummation=%d",sum);
printf("\nSummation=%d",sum); return 0;
return 0; }
}
118
WAP to sort ‘n’ numbers and sort them in ascending order using pointer
119
WAP to count the number of words present in a line of paragraph using
pointer
#include <stdio.h>// without using pointer #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
int main() int main()
{ {
char *ch; char ch[100];
int count=0,i=0; int count=0,i=0;
printf("Enter a line of paragraph:\n"); printf("Enter a line of paragraph:\n");
scanf("%[^\n]",ch); scanf("%[^\n]",ch);
//gets(ch); //gets(ch);
while(ch[i]!='\0') while(*(ch+i)!='\0')
{ {
if(ch[i]==32) if(*(ch+i)==32)
{ {
count++; count++;
} }
i++; i++;
} }
printf("\nTotal no of words=%d",count+1); printf("\nTotal no of words=%d",count+1);
return 0; return 0;
} }
120
Two dimensional Array
Syntax for 2-D array representation:
datatype (* pointer_variable)[size];
let us consider pointer representation of
let us consider an 2-D array:
2-D array:
int x[5][5];
int (*x)[5];
121
C Program to Sort 10 Numbers Using a User-Defined Function and Pointer
#include <stdio.h> }
void sort(int *arr, int size) { printf("\n");
int i, j, temp; }
for (i = 0; i < size - 1; i++) {
for (j = 0; j < size - 1 - i; j++) { int main() {
// Compare and swap if needed int arr[10];
if (*(arr + j) > *(arr + j + 1)) { int i;
temp = *(arr + j); printf("Enter 10 numbers:\n");
*(arr + j) = *(arr + j + 1); for (i = 0; i < 10; i++) {
*(arr + j + 1) = temp; scanf("%d", &arr[i]);
} }
} sort(arr, 10);
} display(arr, 10);
} return 0;
void display(int *arr, int size) { }
printf("Sorted Array: ");
for (int i = 0; i < size; i++) {
printf("%d ", *(arr + i)); // Access elements using pointer arithmetic
122
WAP to input elements of 3X2 matrix and display the elements in matrix order using pointer
#include <stdio.h>
#include <stdlib.h>
int main()
{
int (*A)[5],i,j;
printf("Enter elements of 3X2 array:\n");
for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
{
scanf("%d",*(A+i)+j);
}
}
//Display the elements
for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
{
printf("%d",*(*(A+i)+j));
}
printf("\n");
}
return 0;
}
123
WAP to multiply two mXn and pXq matrix and display the result using pointer
125
#include <stdio.h> int i;
#include <string.h>
#define MAX_STUDENTS 5 // Initialize pointers to the rows of the 2D array
#define MAX_NAME_LENGTH 100 for (i = 0; i < MAX_STUDENTS; i++) {
// User-defined function to sort an array of strings in ascending namePointers[i] = studentNames[i];
order }
void sortNames(char *names[], int n)
{ // Input 5 different student names
char *temp; printf("Enter %d different student names:\n",
for (int i = 0; i < n - 1; i++) { MAX_STUDENTS);
for (int j = i + 1; j < n; j++) { for (i = 0; i < MAX_STUDENTS; i++) {
if (strcmp(names[i], names[j]) > 0) { printf("Name %d: ", i + 1);
// Swap the pointers scanf("%s", studentNames[i]);
temp = names[i]; }
names[i] = names[j];
names[j] = temp; // Sort the names using the user-defined function
} sortNames(namePointers, MAX_STUDENTS);
}
} // Display the sorted names
} printf("\nSorted names in ascending order:\n");
for (i = 0; i < MAX_STUDENTS; i++) {
int main() printf("%s\n", namePointers[i]);
{ }
char
studentNames[MAX_STUDENTS][MAX_NAME_LENGTH]; return 0;
char *namePointers[MAX_STUDENTS]; } 126
Questions:
Write a progmm to read a 3*3 square matrix, find minimum integer
value of a matrix, replace the diagonal elements by the minimum
element and display it using pointer
127
#include <stdio.h> }
}
int main() { }
int matrix[3][3];
int min, i, j; // Replacing diagonal elements with the minimum value
for (i = 0; i < 3; i++) {
// Pointer to the 2D matrix ptr[i][i] = min;
int (*ptr)[3] = matrix; }
129
malloc() Method
malloc() stands for memory allocation.
It is a standard library function in C that allocates a block of memory of a specified size at runtime and
returns a pointer to the beginning of this block.
The contents of the memory block are not initialized, meaning they contain garbage values when first
allocated.
Syntax ptr = (cast-type*) malloc(byte-size)
Example:ptr = (int*) malloc(100 * sizeof(int));
Since the size of int is 4 bytes, this statement will allocate 400 bytes of memory. And, the pointer ptr holds
the address of the first byte in the allocated memory.
130
calloc()
131
realloc() arr = (int*) malloc(n * sizeof(int));
realloc() is a standard library if (arr == NULL) { if (arr == NULL) {
function in C that allows you to printf("Memory allocation printf("Memory reallocation
resize a previously allocated memory failed\n"); failed\n");
block.
return 1; return 1;
It can either increase or decrease the
size of a memory block that was } }
initially allocated using malloc() or for (int i = 0; i < n; i++) { for (int i = 5; i < n; i++) {
calloc().
arr[i] = i + 1; arr[i] = (i + 1) * 2;
If the memory block is enlarged, the
additional memory is uninitialized. } }
Syntax: ptr = (cast-type*) printf("Array before realloc: "); printf("Array after realloc: ");
realloc(byte-size) for (int i = 0; i < n; i++) { for (int i = 0; i < n; i++) {
Example: printf("%d ", arr[i]); printf("%d ", arr[i]);
#include <stdio.h> } }
#include <stdlib.h> printf("\n"); printf("\n");
int main() { n = 10; free(arr);
int *arr; arr = (int*) realloc(arr, n * return 0;
int n = 5; sizeof(int));
}
132
free()
133
malloc() vs calloc()
Attribute malloc() calloc()
Allocates a block of memory of the specified
Allocates memory for an array of elements and
Definition size. Does not initialize the memory (contains
initializes all elements to zero.
garbage values).
One parameter: the total size in bytes of memory Two parameters: the number of elements and the size
Parameters
to allocate. of each element (in bytes).
Does not initialize memory (leaves it with
Initialization Initializes all allocated memory to zero.
garbage values).
Slower due to the extra step of initializing memory to
Performance Generally faster since no initialization is done.
zero.
Suitable for allocating memory when
Ideal when memory needs to be initialized to zero
Use Case initialization is not required (e.g., buffers,
(e.g., arrays or structures).
dynamic arrays).
Example arr = (int*) malloc(5 * sizeof(int)); arr = (int*) calloc(5, sizeof(int));
Memory Allocates a block of memory of the specified size Allocates memory for num elements, each of size
Allocation (in bytes). size bytes.
134
Advantages of Dynamic Memory Allocation :
1. Efficient Memory Usage: DMA allows memory to be allocated only when required, preventing the
wastage of memory by allocating fixed sizes upfront.
[Link] Memory Management: Memory can be allocated and freed dynamically during runtime,
allowing the program to adjust memory usage as needed.
[Link] Allocation During Runtime: DMA enables programs to allocate memory based on
conditions that arise at runtime, such as user input or file sizes.
[Link] for Large Data Structures: It facilitates the creation and management of complex data
structures, such as linked lists, trees, and dynamic arrays, which require flexibility in size.
[Link] of Memory Waste: By allocating memory as needed, DMA avoids wasting memory,
especially in scenarios where the size of data is not known beforehand.
[Link] Handling of Variable-Sized Data: DMA allows for the allocation of memory for data whose
size may vary, such as handling user-generated content or input of unknown length.
[Link] for Complex Data Structures: With DMA, you can create and manage complex, nested data
structures that grow or shrink dynamically, such as dynamic arrays, queues, and graphs.
[Link] Performance: It reduces memory consumption by allocating memory only when needed,
leading to better overall performance, especially in resource-constrained environments.
135
Example
// Program to calculate the sum of n numbers entered by if(ptr == NULL) {
the user
printf("Error! memory not allocated.");
return 1;// terminates the program.
#include <stdio.h>
}
#include <stdlib.h>
printf("Enter elements: ");
for(i = 0; i < n; ++i) {
int main() {
scanf("%d", ptr + i);
int n, i, *ptr, sum = 0;
sum += *(ptr + i);
}
printf("Enter number of elements: ");
printf("Sum = %d", sum);
scanf("%d", &n);
// deallocating the memory
free(ptr);
ptr = (int*) malloc(n * sizeof(int));
return 0;
}
// if memory cannot be allocated
136
Program to Calculate the Sum of n Numbers Using DMA
#include <stdio.h> int main() {
#include <stdlib.h> int n, *arr, sum; sum = calculateSum(arr, n);
int calculateSum(int arr[], int n) printf("Enter number of elements: "); printf("Sum of entered numbers: %d\n",
sum);
{ scanf("%d", &n);
free(arr);
int sum = 0; arr = (int*) malloc(n * sizeof(int));
return 0;
for (int i = 0; i < n; i++) if (arr == NULL) {
}
{ printf("Error! Memory not
allocated.\n");
sum += arr[i];
return 1;
}
}
return sum;
printf("Enter %d numbers:\n", n);
}
for (int i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
137
Write a C program that dynamically allocates memory for an array, accepts n numbers from the user,
sorts them in ascending order using a function, and displays the sorted array .
#include <stdio.h> arr[j] = arr[j + 1]; printf("Enter the number of elements: ");
#include <stdlib.h> arr[j + 1] = temp; scanf("%d", &n);
void read(int *arr, int n) { } arr = (int *)malloc(n * sizeof(int));
printf("Enter %d numbers:\n", n); } if (arr == NULL) {
for (int i = 0; i < n; i++) { } printf("Memory allocation failed.\n");
scanf("%d", &arr[i]); } return 1;
} void display(int *arr, int n) { }
} printf("Sorted array in ascending read(arr, n);
order:\n");
void sort(int *arr, int n) { sort(arr, n);
for (int i = 0; i < n; i++) {
int temp; display(arr, n);
printf("%d ", arr[i]);
for (int i = 0; i < n - 1; i++) { free(arr);
}
for (int j = 0; j < n - 1 - i; j++) { return 0;
printf("\n");
if (arr[j] > arr[j + 1]) { }
}
// Swap elements
int main() {
temp = arr[j];
int *arr, n; 138
Array vs pointer
Array Pointer
The size is fixed at compile time and cannot be changed during The size can be dynamically allocated and modified during
program execution. program execution.
Elements are accessed using index notation (e.g., arr[i]). Elements are accessed via dereferencing the pointer (e.g., *ptr).
An array is initialized at the time of declaration with a predefined A pointer can be initialized with any valid memory address, often
size (e.g., int arr[5]). using dynamic memory allocation.
140