The Wayback Machine - https://web.archive.org/web/20240907043156/https://www.geeksforgeeks.org/applications-of-pointers-in-c-cpp/
Open In App

Applications of Pointers in C

Last Updated : 06 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Pointers in C are variables that are used to store the memory address of another variable. Pointers allow us to efficiently manage the memory and hence optimize our program. In this article, we will discuss some of the major applications of pointers in C.

Prerequisite: Pointers in C.

C Pointers Application

The following are some major applications of pointers in the C programming language:

1. Passing Arguments by Reference

Passing arguments by reference serves two purposes:

i.) to modify the variable in another function.

Example

The below example demonstrates the use of pointers by swapping two numbers.

C
// C program to demonstrate that we can change
// local values of one function in another using pointers.

#include <stdio.h>

void swap(int* x, int* y)
{
    int temp = *x;
    *x = *y;
    *y = temp;
}

int main()
{
    int x = 10, y = 20;
    swap(&x, &y);
    printf("%d %d\n", x, y);
    return 0;
}

Output
20 10

ii.) For Efficiency Purpose

Example

The below example demonstrates the use of pointers to write efficient code.

C
#include <stdio.h>

// function to print an array by passing reference to array
void printArray(int* arr, int n)
{
    // here array elements are passed by reference
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
}

int main()
{
    int arr[5] = { 1, 2, 3, 4, 5 };
    printArray(arr, 5);
    return 0;
}

Output
1 2 3 4 5 

Note: Passing large structure without reference would create a copy of the structure (hence wastage of space). 

2. For Accessing Array Elements

Compiler internally uses pointers to access array elements. We can also use these pointers to access and modify the elements of the given array.

Example

The below example demonstrate the use of pointers to access elements of an array.

C
// C program to demonstrate that compiler
// internally uses pointer arithmetic to access
// array elements.

#include <stdio.h>

int main()
{
    int arr[] = { 100, 200, 300, 400 };

    // Compiler converts below to *(arr + 2).
    printf("%d ", arr[2]);

    // So below also works.
    printf("%d\n", *(arr + 2));

    return 0;
}

Output
300 300

3. To Return Multiple Values

The functions in C can only return a single value, but we can use pointers to return multiple values from a C function.

Example

The below example demonstrates the use of pointers to return square and square root of numbers using pointers.

C
// C program to demonstrate that using a pointer
// we can return multiple values.

#include <math.h>
#include <stdio.h>

void fun(int n, int* square, double* sq_root)
{
    *square = n * n;
    *sq_root = sqrt(n);
}

int main()
{

    int n = 100;
    int sq;
    double sq_root;
    fun(n, &sq, &sq_root);

    printf("%d %f\n", sq, sq_root);
    return 0;
}

Output:

10000
10

4. For dynamic memory Allocation

We can use pointers to dynamically allocate memory i.e Dynamic memory allocation. The advantage of dynamically allocated memory is, it is not deleted until we explicitly delete it.

Example

The below example shows the use of pointers to dynamically allocate memory.

C
// C program to dynamically allocate an
// array of given size.

#include <stdio.h>
#include <stdlib.h>
int* createArr(int n)
{
    int* arr = (int*)(malloc(n * sizeof(int)));
    return arr;
}

int main()
{
    int* pt = createArr(10);
    return 0;
}

FAQs on Application of Pointers in C

Q1. What are the uses of a pointer?

Answer:

Pointer is used in the following cases
             i) It is used to access array elements
            ii) It is used for dynamic memory allocation.
           iii) It is used in Call by reference
           iv) It is used in data structures like trees, graph, linked list etc.

Q2. Are pointers integer?

Answer:

No, pointers are not integers. A pointer is an address and a positive number.

Q3. What does the error ‘Null Pointer Assignment’ means and what causes this error?

Answer:

As null pointer points to nothing so accessing a uninitialized pointer or invalid location may cause an error.

Q4. How pointer variables are initialized?

Answer:

Pointer variables are initialized by one of the following ways.
             I. Static memory allocation
            II. Dynamic memory allocation

Q5. What is pointer to a pointer?

Answer:

If a pointer variable points another pointer value. Such a situation is known as a pointer to a
pointer.
Example:
   int *p1,**p2,v=10;
   P1=&v; p2=&p1;
   Here p2 is a pointer to a pointer

Q6. What is an array of pointers?

Answer:

If the elements of an array are addresses, such an array is called an array of pointers.



Previous Article
Next Article

Similar Reads

Near, Far and Huge Pointers in C
In older times, the intel processors had 16-bit registers but the address bus was 20-bits wide. Due to this, the registers were not able to hold the entire address at once. As a solution, the memory was divided into segments of 64 kB size, and the near pointers, far pointers, and huge pointers were used in C to store the addresses. There are old co
4 min read
Program to reverse an array using pointers
Prerequisite : Pointers in C/C++ Given an array, write a program to reverse it using pointers . In this program we make use of * operator . The * (asterisk) operator denotes the value of variable . The * operator at the time of declaration denotes that this is a pointer, otherwise it denotes the value of the memory location pointed by the pointer .
4 min read
Difference between pointer to an array and array of pointers
Pointer to an array: Pointer to an array is also known as array pointer. We are using the pointer to access the components of the array. int a[3] = {3, 4, 5 }; int *ptr = a; We have a pointer ptr that focuses to the 0th component of the array. We can likewise declare a pointer that can point to whole array rather than just a single component of the
4 min read
Features and Use of Pointers in C/C++
Pointers store the address of variables or a memory location. Syntax: datatype *var_name; Example: pointer "ptr" holds the address of an integer variable or holds the address of memory whose value(s) can be accessed as integer values through "ptr" int *ptr; Features of Pointers: Pointers save memory space.Execution time with pointers is faster beca
2 min read
Move all zeroes to end of array using Two-Pointers
Given an array of random numbers, Push all the zero’s of the given array to the end of the array. For example, if the given arrays is {1, 0, 2, 6, 0, 4}, it should be changed to {1, 2, 6, 4, 0, 0}. The order of all other elements should be the same.Examples: Input: arr[]={8, 9, 0, 1, 2, 0, 3} Output: arr[]={8, 9, 1, 2, 3, 0, 0} Explanation: Swap {0
6 min read
How many levels of pointers can we have in C/C++
Prerequisite: Pointer in C and C++, Double Pointer (Pointer to Pointer) in CA pointer is used to point to a memory location of a variable. A pointer stores the address of a variable and the value of a variable can be accessed using dereferencing of the pointer. A pointer is generally initialized as: datatype *variable name; This above declaration i
7 min read
Why do we need reference variables if we have pointers
Pointers: A pointer is a variable that holds memory address of another variable. A pointer needs to be de referenced with * operator to access the memory location it points to.References: A Reference can be called as a constant pointer that becomes de referenced implicitly. When we access the reference it means we are accessing the storage.Why do w
4 min read
Unusual behaviour with character pointers
In C++, cout shows different printing behaviour with character pointers/arrays unlike pointers/arrays of other data types. So this article will firstly explain how cout behaves differently with character pointers, and then the reason and the working mechanism behind it will be discussed. Example 1: C/C++ Code // C++ program to illustrate difference
5 min read
How to Declare and Initialize an Array of Pointers to a Structure in C?
Prerequisite: Structure in CArray in C In C language, arrays are made to store similar types of data in contiguous memory locations. We can make arrays of either primitive data types, like int, char, or float, or user-defined data types like Structures and Unions. We can also make arrays of pointers in C language. Today we will learn how to create
8 min read
How to declare a Two Dimensional Array of pointers in C?
A Two Dimensional array of pointers is an array that has variables of pointer type. This means that the variables stored in the 2D array are such that each variable points to a particular address of some other element. How to create a 2D array of pointers: A 2D array of pointers can be created following the way shown below. int *arr[5][5]; //creati
3 min read
Passing Pointers to Functions in C
Prerequisites: Pointers in CFunctions in C Passing the pointers to the function means the memory location of the variables is passed to the parameters in the function, and then the operations are performed. The function definition accepts these addresses using pointers, addresses are stored using pointers. Arguments Passing without pointer When we
2 min read
Output of C programs | Set 64 (Pointers)
Prerequisite : Pointers in C Question 1 : What will be the output of following program? C/C++ Code #include &amp;quot;stdio.h&amp;quot; int main() { char a[] = { 'A', 'B', 'C', 'D' }; char* ppp = &amp;amp;a[0]; *ppp++; // Line 1 printf(&amp;quot;%c %c &amp;quot;, *++ppp, --*ppp); // Line 2 } OPTIONS: a)C B b)B A c)B C d)C A OUTPUT: (d) C A Explanat
3 min read
What are Wild Pointers? How can we avoid?
Uninitialized pointers are known as wild pointers because they point to some arbitrary memory location and may cause a program to crash or behave unexpectedly. Example of Wild PointersIn the below code, p is a wild pointer. C/C++ Code // C program that demonstrated wild pointers int main() { /* wild pointer */ int* p; /* Some unknown memory locatio
2 min read
Why Does C Treat Array Parameters as Pointers?
In C, array parameters are treated as pointers mainly to, To increase the efficiency of codeTo save time It is inefficient to copy the array data in terms of both memory and time; and most of the time, when we pass an array our intention is to just refer to the array we are interested in, not to create a copy of the array. The following two definit
2 min read
Difference between Arrays and Pointers
The array and pointers are derived data types that have lots of differences and similarities. In some cases, we can even use pointers in place of an array, and arrays automatically get converted to pointers when passed to a function. So, it is necessary to know about the differences between arrays and pointers to properly utilize them in our progra
7 min read
Pointers vs References in C++
Prerequisite: Pointers, References C and C++ support pointers, which is different from most other programming languages such as Java, Python, Ruby, Perl and PHP as they only support references. But interestingly, C++, along with pointers, also supports references. On the surface, both references and pointers are very similar as both are used to hav
5 min read
Dangling, Void , Null and Wild Pointers in C
In C programming pointers are used to manipulate memory addresses, to store the address of some variable or memory location. But certain situations and characteristics related to pointers become challenging in terms of memory safety and program behavior these include Dangling (when pointing to deallocated memory), Void (pointing to some data locati
6 min read
Pointers vs Array in C++
Arrays and pointers are two derived data types in C++ that have a lot in common. In some cases, we can even use pointers in place of arrays. But even though they are so closely related, they are still different entities. In this article, we will study how the arrays and pointers are different from each other in C++. What is an Array?An array is the
3 min read
C Pointers
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 in C. In this article, we will discuss C pointers in detail, their
14 min read
Array of Pointers in C
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_nam
6 min read
Program to Reverse a String using Pointers
Given a string, the task is to reverse this String using pointers. Examples: Input: GeeksOutput: skeeGInput: GeeksForGeeksOutput: skeeGroFskeeGApproach: This method involves taking two pointers, one that points at the start of the string and the other at the end of the string. The characters are then reversed one by one with the help of these two p
2 min read
C++ string class and its applications
In C++ we can store string by one of the two ways – C style stringsstring class (discussed in this post) In this post, the second method is discussed. string class is part of C++ library that supports a lot much functionality over C style strings. C++ string class internally uses char array to store character but all memory management, allocation,
6 min read
C++ String Class and its Applications
C++ string class and its applications have more functions as discussed in this article String vs Character Array In C++, in addition to a character array, there exists a similar kind of way to implement string, that is using a string class which is a part of C++ standard library.We need to add a header file to implement string using string class. T
4 min read
INT_MAX and INT_MIN in C/C++ and Applications
Most of the time, in competitive programming, there is a need to assign the variable, the maximum or minimum value that data type can hold, but remembering such a large and precise number comes out to be a difficult job. Therefore, C/C++ has certain macros to represent these numbers, so that these can be directly assigned to the variable without ac
7 min read
C Programming Language Tutorial
In this C Tutorial, you’ll learn all C programming basic to advanced concepts like variables, arrays, pointers, strings, loops, etc. This C Programming Tutorial is designed for both beginners as well as experienced professionals, who’re looking to learn and enhance their knowledge of the C programming language. What is C?C is a general-purpose, pro
8 min read
C Programs
To learn anything effectively, practicing and solving problems is essential. To help you master C programming, we have compiled over 100 C programming examples across various categories, including basic C programs, Fibonacci series, strings, arrays, base conversions, pattern printing, pointers, and more. These C Examples cover a range of questions,
8 min read
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
Since C is a structured language, it has some fixed rules for programming. One of them includes changing the size of an array. An array is a collection of items stored at contiguous memory locations.  As can be seen, the length (size) of the array above is 9. But what if there is a requirement to change this length (size)? For example,  If there is
9 min read
Operators in C
In C language, operators are symbols that represent operations to be performed on one or more operands. They are the basic components of the C programming. In this article, we will learn about all the built-in operators in C with examples. What is a C Operator?An operator in C can be defined as the symbol that helps us to perform some specific math
14 min read
Data Types in C
Each variable in C has an associated data type. It specifies the type of data that the variable can store like integer, character, floating, double, etc. Each data type requires different amounts of memory and has some specific operations which can be performed over it. The data type is a collection of data with values having fixed values, meaning
7 min read
C Language Introduction
C is a procedural programming language initially developed by Dennis Ritchie in the year 1972 at Bell Laboratories of AT&amp;T Labs. It was mainly developed as a system programming language to write the UNIX operating system. The main features of the C language include: General Purpose and PortableLow-level Memory AccessFast SpeedClean SyntaxThese
6 min read
Article Tags :