Chapter 12 Pointers
Chapter 12 Pointers
Pointers In C
What is a Pointer?
• Pointers are one of the core components of the C programming language. A pointer
can be used to store the memory address of other variables, functions, or even other
pointers. The use of pointers allows low-level memory access, dynamic memory
allocation, and many other functionality
• A pointer is defined as a derived data type that can store the address of other C
variables or a memory location. We can access and manipulate the data stored in
that memory location using pointers.
• Syntax of C Pointers
• datatype * ptr;
• where
• ptr is the name of the pointer.
• datatype is the type of data it is pointing to.
Accessing the address of a variable
• Once we declare a variable , then it will be stored in the memory.The address of a
variable can be obtainrd using the address operator(&).
• The & is a unary operator that returns the memory address of its operand.
• Ex: int i =5;
Suppose if I stored in memory location 20560,then we can use
Printf(“The address of i is:%u”, &i);
It prints 20560.we have used %u to print the address
Declaring pointers and initializing
Like variables, pointers in c have to be declsred before they can be used in program.
Pointers can be named anything we want as long as they obey C’s naming rules.The
general format for declaring a pointers is
Syntax: <datatype>*<pointer name>;
Ex: int *intpointer; // pointer to an integer
float *f; //pointer to a float
Initializing a pointer:
• Pointer initialization is the process where we assign some initial value to the pointer variable. We
generally use the ( &: ampersand ) addressof operator to get the memory address of a variable and
then store it in the pointer variable.
• Example
• Example
row3
#include <stdio.h>
// Drivers code
int main()
{
int arr1[5][5] = { { 0, 1, 2, 3, 4 },
{ 2, 3, 4, 5, 6 },
{ 4, 5, 6, 7, 8 },
{ 5, 4, 3, 2, 6 },
{ 2, 5, 4, 3, 1 } };
int* arr2[5][5]; // Initialising each element of the // pointer array with the address of // element present in the other array
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
arr2[i][j] = &arr1[i][j];
} } // Printing the array using // the array of pointers
printf("The values are\n");
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
printf("%d ", *arr2[i][j]);
}
printf("\n");
}
return 0;
}
Pointer expressions
• In general , expressions involving pointers confirm to the same rules as other
expressions. Let us discuss the few
• 1) Pointer Assignments
• We can assign one pointer to another pointer, which is similar of assigning
one variable value to an another variable.when both pointers are same type
then we go for assignment
• Ex:
int a =10,b=20;
Int *ptr1,*ptr2;
Ptr1=&a;
Ptr2=&b;
2) Pointer Comparison
• We can compare two pointers in a relational expression for ex: , givrn
two pointers ptr1 and ptr2.
• Int a[5] = {10,20,30,40,50}
• Int *ptr1,*ptr2;
• Ptr1 = &a[0];
• Ptr2 = &a[3];
a[0]
10 a[1]
20 a[2]
30 a[3]
40 a[4]
50
4000 4010
Cont….
• If(ptr1 <ptr2)
printf(“ptr1 points to lower memory than ptr2 \n”);
Else
printf(“ptr1 points to lower memory than ptr2 \n”);
3) Pointer arithmetic
• Pointer Arithmetic in C refers to the ability to perform arithmetic
operations on pointers. Since pointers represent memory addresses,
pointer arithmetic allows you to manipulate these memory addresses
directly. This is especially useful when working with arrays or dynamically
allocated memory, as the elements in these data structures are stored in
contiguous memory locations.
• Example1: pointer arithmetic-incrementing pointer, decrementing
pointer, adding a number to the pointer,subtracting a number from
pointer
• Let ptr be an integer pointer with current value of 2000
2000
Ptr ---------------pointer name
int main() {
int arr[] = {10, 20, 30, 40, 50};
return 0;
}
Valid operations on pointer
• Int a,b; // two integer variables
• Int *ptr1,*ptr2; // two pointer variables
#include <stdio.h>
int main()
{
// Initialize an array of pointers to strings
char* arr[4]
= { "C++", "Java", "Python", "JavaScript" };
int n = sizeof(arr) / sizeof(arr[0]);
// Print the strings using the pointers
printf("Array Elements:\n");
for (int i = 0; i < n; i++) {
printf("%s\n", arr[i]);
}
return 0;
}
Pointer to pointer
• The pointer to a pointer in C is used when we want to store the address of another
pointer. The first pointer is used to store the address of the variable. And the
second pointer is used to store the address of the first pointer. That is why they are
also known as double-pointers. We can use a pointer to a pointer to change the
values of normal pointers or create a variable-sized 2-D array. A double pointer
occupies the same amount of space in the memory stack as a normal pointer
• Declaration of Pointer to a Pointer in C
• Declaring Pointer to Pointer is similar to declaring a pointer in C. The difference is
we have to place an additional ‘*’ before the name of the pointer.
**Output:**
12345
• 3. **Function Returning a Pointer**:A function can return a pointer, allowing dynamic memory allocation, array handling, or
returning the address of a local static variable.
Example: Function returning a pointer
#include <stdio.h>
int* findMax(int *arr, int size) {
int *max = arr;
for (int i = 1; i < size; i++) {
if (*(arr + i) > *max) {
max = arr + i; // Update pointer to point to the new max element
}
}
return max; // Return the pointer to the maximum element
}
int main() {
int arr[] = {10, 20, 30, 40, 50};
int *maxElem = findMax(arr, 5); // Get pointer to the max element
printf("Maximum element: %d\n", *maxElem); // Dereference to print the value
return 0;
}
**Output:**
Maximum element: 50
• 4. **Pointer to a Function**
• You can create a pointer to a function, which allows you to call functions dynamically (e.g., in callback mechanisms
or dynamic dispatch).
Example: Pointer to a function
#include <stdio.h>
// Function to add two numbers
int add(int a, int b) {
return a + b;
}
int main() {
// Declare a function pointer and assign it to the add function
int (*func_ptr)(int, int) = add;
// Use the function pointer to call the function
int result = func_ptr(5, 3); // Equivalent to add(5, 3)
printf("The sum is: %d\n", result);
return 0;
}
Output:
• The sum is: 8
• 5. **Arrays of Pointers to Functions You can have an array of function pointers. This is commonly used in scenarios like
implementing command patterns, or creating a table of functions for handling different cases (e.g., a menu system).
Example: Arrays of pointers to functions
#include <stdio.h>
// Functions to perform different operations
int add(int a, int b) { return a + b; }
int subtract(int a, int b) { return a - b; }
int multiply(int a, int b) { return a * b; }
int main() {
// Array of function pointers
int (*operations[])(int, int) = {add, subtract, multiply};
int x = 10, y = 5;
// Call each function using the array of function pointers
printf("Add: %d\n", operations[0](x, y)); // add(x, y)
printf("Subtract: %d\n", operations[1](x, y)); // subtract(x, y)
printf("Multiply: %d\n", operations[2](x, y)); // multiply(x, y)
return 0;
}
Output:
Add: 15
Subtract: 5
Multiply: 50
Command line arguments
• The most important function of C is the main() function. It is mostly defined with a return type of int and
without parameters.
int main() {
...
}
We can also give command-line arguments in C. Command-line arguments are the values given after the name of
the program in the command-line shell of Operating Systems. Command-line arguments are handled by the
main() function of a C program.
To pass command-line arguments, we typically define main() with two arguments: the first argument is the
number of command-line
arguments and the second is a list of command-line arguments.
Syntax
int main(int argc, char *argv[]) { /* ... */ }
or
int main(int argc, char **argv) { /* ... */ }
EX
• // C program named mainreturn.c to demonstrate the working
• // of command line arguement
• #include <stdio.h>
// defining main with arguments
int main(int argc, char* argv[])
{
printf("You have entered %d arguments:\n", argc);
for (int i = 0; i < argc; i++) {
printf("%s\n", argv[i]);
}
return 0;
}
Properties of Coomand line
arguments
• They are passed to the main() function.
• They are parameters/arguments supplied to the program when it is
invoked.
• They are used to control programs from outside instead of hard
coding those values inside the code.
• argv[argc] is a NULL pointer.
• argv[0] holds the name of the program.
• argv[1] points to the first command line argument and argv[argc-1]
points to the last argument.
Advantages and disadvantages of
pointers
• Advantages
• Pointers provide direct access to memory
• Reduces the execution time of the program
• Pointers reduce length and complexity of programs
• Disadvantages
• Pointers are little complex to understand
• Can lead to various errors
• If incorrect value is been provided than it may cause memory
corruption