0% found this document useful (0 votes)
8 views31 pages

Chapter 12 Pointers

pointers

Uploaded by

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

Chapter 12 Pointers

pointers

Uploaded by

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

Chapter 12

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

int var = 10;


int * ptr;
ptr = &var;
We can also declare and initialize the pointer in a single step. This method is called pointer definition
as the pointer is declared and initialized at the same time.

• Example

• int *ptr = &var;


• EX: int I =5; // declaring normal variable
• int *ptr; // declaring a pointer
Accessing a variable through its
pointer
• The value of the variable which is pointed by a pointer can be accessed and manipulated by using
the pointer variable. You need to use the asterisk (*) sign with the pointer variable to access and
manipulate the variable's value.
• #include <stdio.h>
int main()
{ int x = 10; // Pointer declaration and initialization
int * ptr = & x; // Printing the current value
printf("Value of x = %d\n", * ptr);
// Changing the value
* ptr = 20; // Printing the updated value
printf("Value of x = %d\n", * ptr);
return 0;
}
Pointers and arrays
• Pointers and single- dimensional arrays
• The compiler allocates Continuous memory locations for all the
elements of the array.
• The base address = first element address (index 0) of the array.
• For Example − int a [5] = {10, 20,30,40,50};
EX:
#include<stdio.h>
main ( ){
int a[5];
int *p,i;
printf ("Enter 5 lements");
for (i=0; i<5; i++)
scanf ("%d", &a[i]);
p = &a[0];
printf ("Elements of the array are");
for (i=0; i<5; i++)
printf("%d", *(p+i));
•}
Pointers and two- dimensional
arrays
• We know that 2d arrays have two subscripts. The first subscript refers to the row and
second subscript refers to the column
• Ex: int A[4][3];
• In the above declaration , array A having 4 rows and 3 columns
int A[4][3] = {{10,20,30},{40,50,60},{70,80,90},{100,110,120}};
The complete arrangement of the array is shown below:
co10 co11 co12
10 20 30
Row0 40 50 60
Row1 70 80 90
Row2 100 110 120

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

2002 2006 2010 2014 2018


Ptr1 = &a[0]2002
ptr1 2014
ptr2 ptr2=&a[3]

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

4028---------------- ptr’s address


Ex:
• Main()
{
Int n=10;
Int *ptr;
Ptr=&n;
Ptr++;
Printf(“%u \n”,ptr); (NOTE:%u format specifier to address)
}
N=10(addr2002) ptr(2002addr(4015))
After ptr++;
N=10(ADDR2002) ptr(2006addr(4015))
Subtracting a pointer from another pointer
• #include <stdio.h>

int main() {
int arr[] = {10, 20, 30, 40, 50};

int *ptr1 = &arr[0]; // points to arr[0]


int *ptr2 = &arr[3]; // points to arr[3]

// Subtracting the pointers


ptrdiff_t diff = ptr2 - ptr1;

printf("Difference between ptr2 and ptr1: %ld\n", diff); // Output: 3

return 0;
}
Valid operations on pointer
• Int a,b; // two integer variables
• Int *ptr1,*ptr2; // two pointer variables

• 1) ptr1=ptr1++; //incrementing a pointer


• 2) ptr1= ptr1--; // decrementing a pointer
• 3) ptr1=ptr1+a; // adding a number to a pointer
• 4) ptr1= ptr1-b; // subtracting number from a pointer
• 5) ptr1-ptr2; // subtracting a pointer from another
Arrays of pointers
• In C, a pointer array is a homogeneous collection of indexed pointer variables that
are references to a memory location.
• It is generally used in C Programming when we want to point at multiple memory
locations of a similar data type in our C program.
• We can access the data by dereferencing the pointer pointing to it.

• Syntax: pointer_type *array_name [array_size];


• Here,

• pointer_type: Type of data the pointer is pointing to.


• array_name: Name of the array of pointers.
• array_size: Size of the array of pointers.
To illustrate the usage of array of
pointers
• // C program to demonstrate the use of array of pointers
#include <stdio.h>
int main()
{
// declaring some temp variables
int var1 = 10;
int var2 = 20;
int var3 = 30;
// array of pointers to integers
int* ptr_arr[3] = { &var1, &var2, &var3 };
// traversing using loop
for (int i = 0; i < 3; i++) {
printf("Value of var%d: %d\tAddress: %p\n", i + 1, *ptr_arr[i], ptr_arr[i]);
}
return 0;
}
Array of pointers to strings
• In C, arrays are data structures that store data in contiguous memory locations. Pointers are variables that
store the address of data variables. We can use an array of pointers to store the addresses of multiple
elements. In this article, we will learn how to create an array of pointers to strings in C.

• Array of Pointers to Strings in C


• An array of pointers to strings is a data structure where each element is a pointer that points to a string. It
is a very effective technique when we want to point at different memory locations of the same data type
like a string.
Syntax to Create an Array of Pointers to Strings in C
• To create an array of pointers to strings in C we can use the following syntax: char * arr[size]
={ "String1", "String2", ....}
• Here,
char*: is the type of pointers we will store in the array.
arr: is the name of the array of pointers.
size: is the size of the array of pointers.
• // C Program to Create an Array of Pointers to Strings

#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.

data_type_of_pointer **name_of_variable = & normal_pointer_variable;


Ex:int val = 5;
int *ptr = &val; // storing address of val to pointer ptr.
int **d_ptr = &ptr; // pointer to a pointer declared
// which is pointing to an integer.
• // C program to demonstrate pointer to pointer
• #include <stdio.h>
int main(){
int var = 789; // pointer for var
int* ptr2;
// double pointer for ptr2
int** ptr1;
// storing address of var in ptr2
ptr2 = &var;
// Storing address of ptr2 in ptr1
ptr1 = &ptr2;
// Displaying value of var using
// both single and double pointers
printf("Value of var = %d\n", var);
printf("Value of var using single pointer = %d\n", *ptr2);
printf("Value of var using double pointer = %d\n", **ptr1);
return 0;
}

Pointers and functions
Pointers are a powerful feature in C, especially when used in conjunction with functions. They allow for more
efficient memory management and provide a means to modify variables inside functions, pass large data structures
efficiently, and implement dynamic behavior.
• 1. **using Pointers as Function Parameters**:Using pointers as function parameters allows you to modify the
actual values of variables from within a function. This is particularly useful when you want to pass large structures
or arrays to a function without copying them, or when you want to return multiple values from a function.
Example: Modifying a value using a pointer as a parameter
#include <stdio.h>
void modifyValue(int *ptr) {
*ptr = 20; // Dereferencing the pointer to modify the value
}
int main() {
int x = 10;
printf("Before function call: x = %d\n", x);
modifyValue(&x); // Passing address of x
printf("After function call: x = %d\n", x);
return 0;
}
Output:
Before function call: x = 10
Passing an Arrays as an Argument to function
• 2. **Passing Arrays as Function Arguments**:arrays are passed to functions as pointers, so passing an array to a function is essentially
passing a pointer to the first element of the array.
• Example: Passing an array to a function
#include <stdio.h>
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
printArray(arr, 5); // Passing array to function
return 0;
}

**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

You might also like