×

Features and Use of Pointers in C/C++

What is a pointer?

A pointer is mainly used to store the address of another variable. The * operator creates a pointer variable, which points to a data type (like an int) of the same type. The pointer is given the address of the variable you are working with.

However, each variable has its address in addition to its value (or, put, where it is in the Memory). The address can be obtained by prefixing the variable name with an ampersand (&).

The Use of Pointers in C/C++

A variable's address will appear utterly random if you print it on the screen (moreover, it can be different from run to run). Computer memory consists of bytes. Each byte has a fixed number of bits, 8 for most types of computers. A number identifies each byte called its address. Variables in a C or C++ program correspond to a series of bytes with consecutive addresses.

The lowest of these consecutive addresses is the address of the variable. A pointer is a variable that holds an address. Pointers to void hold addresses of bytes, and pointers to a type of hold addresses of variables of that type. Address 0 is not considered to be a valid address. But it's common in C and C++ for pointers to be set to address 0, which means they are not pointing to anything.

Technically, a pointer is the same thing as a size_t(unsigned long long) variable. We use them to store memory addresses. But there is more to it than just that.

You see, to the programmer and the compiler, a pointer represents two things:

1. The memory address that it points to.

2. The "type" of the data it points to.

How does the "type of the data" help?

  • It helps with readability (If I see an (int*).
  • It helps with pointer arithmetic.

E.g., in a 32bit Environment, an int pointer would jump 4 bytes ahead when you do a pointer++. Because sizeof(int)=4, but a char pointer would only jump 1 byte because the size of(char) is 1.

There are two types of pointers:

1)Pointers to primitive types.

2)Pointers to user-defined types.

But the data that a pointer holds is always the same kind-" Memory address."

Syntax:

datatype *var_name;

Example:

int *ptr;

Where int is the datatype and ptr is the pointer.

Declaration

Int *ptr=&var;

A pointer is initialized using a variable address after being declared, just like standard variables. The outcomes are unexpected and fatal if pointers in C programming are not uninitialized and utilized in the program.

We put the ampersand (&) operator before the name of a variable whose address we need to obtain to obtain its address. The syntax for initializing pointers is as follows.

Program

#include <iostream>
#include<bits/stdc++.h>
using namespace std;


int main()
{
    int a=10;
    int *ptr=&a;
    cout<<*ptr<<endl;


    return 0;
}

Output:

10

Another way to declare the pointer:

#include <iostream>
#include<bits/stdc++.h>
using namespace std;


int main()
{
    int a=10;
    int *ptr;
    ptr=&a;
    cout<<*ptr<<endl;


    return 0;
}

Output:

10

If the value is changed in the pointer, then changes will also be reflected in the original variable.

#include <iostream>
#include<bits/stdc++.h>
using namespace std;


int main()
{
    int a=10;
    int *ptr;
    ptr=&a;
    *ptr=20;
    cout<<"Pointer: "<<*ptr<<endl;
    cout<<"Variable: "<<a<<endl;


    return 0;
}

Output:

Pointer: 20
Variable: 20

If a variable is changed, pointer will also be changed.

#include <iostream>
#include<bits/stdc++.h>
using namespace std;


int main()
{
    int a=10;
    int *ptr;
    ptr=&a;
    a=20;
    cout<<"Pointer: "<<*ptr<<endl;
    cout<<"Variable: "<<a<<endl;


    return 0;
}

Output:

Pointer: 20
Variable: 20

Features of pointers

  • Pointers conserve Memory.
  • Because data are modified with addresses or direct access to memory locations, pointers have faster execution times.
  • The pointers provide efficient access to Memory. The Memory is both assigned and released by the pointer. Thus, it may be claimed that the Memory of pointers is allocated dynamically.
  • Data structures employ pointers. They can represent both two-dimensional and multi-dimensional arrays.
  • Pointers allow access to any array without considering the subscript range.
  • For handling files, pointers are utilized.
  • To allocate Memory dynamically, pointers are utilized.

Pointer Types in C

The many types of pointers in C are as follows:

  • Null Pointer: We can produce a null pointer by assigning a null value at the pointer declaration. When the pointer has no given address, this approach is helpful. The value 0 is always present in a null pointer.
  • Void Pointer: A void pointer is also known as a generic pointer in C programming. There is a variety of data types for it. The keyword void creates a pointer to a void. Any variable's address may be stored in it.
  • Wild pointer: If a pointer is not being initialized to anything, it is referred to as a wild pointer. These C pointer types are inefficient because they might point to an unidentified memory location, which could interfere with our program and cause it to crash. When using wild pointers, one should always exercise caution.

Advantages of pointers

  • For gaining access to memory regions, pointers are helpful.
  • An array structure's elements can be accessed effectively via pointers.
  • Both deallocation and dynamic memory allocation require pointers.
  • Complex data structures, like linked lists, graphs, trees, etc., are created using pointers.

Drawback of pointers

Pointers are very powerful, but with great power comes great danger. You could accidentally overwrite a system file just because your pointer contained a garbage value. Bugs are common in software; if even one of those bugs contains naked pointers, your computer is at risk.

So, to avoid that danger, HLLs hide pointers behind the implemented data structures and discourage programmers from using them. They encapsulate and obscure pointers so much that you could be programming for thirty years, and you wouldn't realize that you were using pointers.

For all practical purposes, the APIs will suffice. But if you are trying to super-optimize your program, you should investigate the low-level languages and pointers. If you use the pointer such that efficiency would suffer due to extra overhead before reaching the target, you are using pointers incorrectly.

Uses of pointers

  1. Pointers can save space

    Space is very precious & saving space leads to gaining time and, thus, better performance. Suppose you're working with very large data types or you have yourself have created an enormous object. Now, if you want to pass this object to a function, then the compiler will generate a copy of this object in the Memory, then this copy will be passed to the function & then the processing on the value will begin. In this way, you need to use the Memory efficiently because you must create a copy of such a large object without any good reasons. But suppose you pass the address of this variable to the target function. In that case, the processing will be done directly on the original object & hence no time or Memory will be wasted on the duplication of the original object. Thus speed & space efficiency is gained.
  2. They can increase speed during iterative traversal

    For example, if you wish to traverse the array, then you'll write a for loop to iterate the index value, but in actuality, you are incrementing the memory address. So, if you're performing conscious back-end coding, then instead of first incrementing the index & then updating the memory address, you can directly access the following memory location & hence performance improvement.
  3. Changes made are observed everywhere

    Suppose you have a program with independent threads. Now instead of creating a copy of the same data for each one, you provide them with the address of the original value & thus, if any change is made to the value, then every thread will get the latest updates.
  4. Reading variables not in the same scope

    Using pointers, you can access variables which were not declared in the same scope.
  5. Another reason for using pointers is that they enable dynamic memory allocation. For the allocation of dynamic memory, pointers are required. When working with an unknown amount of data, dynamic memory allocation comes in handy since it enables you to build variables, arrays, and more complicated data structures in memory while the program is executing.
  6. Pointers can also be used in storing elements in the array and accessing those elements from the array. Because the array variable also has an address that a pointer can point to, and the array can be navigated using a pointer.

Example:

#include <stdio.h>
int main() {
    int a[5];


    printf("Enter elements: ");
    for (int i = 0; i < 5; ++i)
        scanf("%d", a + i);


    printf("You entered: \n");
    for (int i = 0; i < 5; ++i)
        printf("%d\n", *(a + i));
    return 0;
}

Output:

Enter elements: 1 2 3 4 5
You entered: 
1
2
3
4
5

Summary

Pointers are used for memory purposes; when using normal data types, you're reserving a memory location for them, whether you use them once or several times. So, with an extensive program would significantly affect the Memory, making the program slower or demanding more Memory from the machine.

Pointers are very useful, and there is a must when going to next-level programming, unlike other languages like java which doesn't contain pointers. Therefore, pointers are a complex and yet most helpful thing in C and C++ programming languages.


Related Topics

C++ Prime number program

In this lesson, you'll learn how to verify whether a given number is a prime number or not in C++, and you'll obtain code to do it. What is the definition...

3 minutes read.

Palindrome using Do-while loop in C++

What is Palindrome? A palindrome is a word, number, phrase, or other sequence of letters that reads the same backward as forward, such as 101 or MOM. Like other programming languages, C++...

5 minutes read.

Inheritance Program in C++

What is Inheritance? Inheritance is the ability of a class to inherit traits and properties from another class. One of the most crucial aspects of Object-Oriented Programming is inheritance. The ability or...

9 minutes read.

C++ Program For FCFS (First Come First Serve)

The most basic scheduling technique is FCFS, often known as "FIFO (First In, First Out)". In this procedure, the first one is utilized and executed first, while the second one...

4 minutes read.

Upcasting and Downcasting in C++

With the help of various examples in the C++ programming language, this section will cover Upcasting and Downcasting. Upcasting and downcasting, on the other hand, are two forms of object typecasting. Consider...

3 minutes read.

Features and Use of Pointers in C/C++

What is a pointer? A pointer is mainly used to store the address of another variable. The * operator creates a pointer variable, which points to a data type (like an...

7 minutes read.

ATM machine program in C++ using functions

Automated Teller Machines (ATMs) carry out daily financial transactions. They are straightforward and simple, allowing customers to complete self-service transactions quickly. ATMs can then be used to withdraw cash, deposit...

3 minutes read.

C++ find missing in the second array

Given two arrays A and B of sizes n and m. Find the elements from array A that are not present in array B. Example Input : a[] = {1, 2, 3, 5,...

3 minutes read.

Initialize Array of objects with parameterized constructors in C++

Initialize Array of objects with parameterized constructors in C++ When a class is defined, only the specification for the object is specified; no memory or capacity is allocated. You need to...

3 minutes read.

For Loop Examples in C++

For Loop A for loop is a repetitive control structure that allows you to create a loop to execute a specific number of times efficiently. The syntax of for loop In C++, a...

6 minutes read.

C++ Program to find the product array puzzle

Write a C++ program to form a product array from arr[] where product[i] is the product of all the array elements except arr[i]. Example Input: arr[]  = {10, 3, 5, 6,...

6 minutes read.

Initialization of Data Members

In this tutorial, we'll look at how to initialise static member variables in C++. Static members, such as functions or variables, can be added to C++ classes. After declaring the...

1 minute read.

C++ File Handling

File handling is a mechanism that manipulates the data stored in files. File handling store output data from the program to external file and read file data to the program. There...

3 minutes read.

Const Keyword in C++

The const programming language keyword will be covered in this section. The constant value that cannot change during program execution is defined using the const keywords. It implies that once...

9 minutes read.

C++ STL Components

C++ STL Components In today’s article, we are going to learn about all the points things that is related to STL in C++ so stay connected because you are going to...

6 minutes read.

Similarities between C++ and Java

People who are preparing for software engineering roles must have come across either one of these languages because as all the companies do not accept python for hiring a fresher...

3 minutes read.

Armstrong Number using While Loop in C++

What is while Loop? A while loop or while statement repeats all code of its body as long as a specific condition is satisfied. The loop ends if or when the...

4 minutes read.

How to find the length of the vector in C++

Like dynamic arrays, vectors can automatically adjust their size when an element is added or removed, and the container manages its storage. Because vector items are stored in contiguous storage, iterators...

3 minutes read.

Reverse a Number in C++

In this tutorial, you'll learn how to utilize a C++ program to reverse a number entered by a user at runtime. Because there are various ways to write a C++...

3 minutes read.

Pthreads or POSIX Threads in C++

The thread API for C/C++ is implemented by pthreads or POSIX threads. It enables the multithreading system, which enables parallel and distributed processing, and the creation of new concurrent process...

3 minutes read.