×

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

Structured Binding in C++

Structured binding is the new feature of C++ 17. It is used to bind the specified name with an element of the initializer. Structure binding is used to declare multiple...

3 minutes read.

Dynamic Memory Allocation in C++

In some programming situations, the number of data items changes as the program is running, which is known as dynamic data or input. Consider a real-world situation where a program...

3 minutes read.

Multiple Inheritance

C++ Multiple Inheritance Multiple inheritance is such an inheritance in which a derived class inherits properties of more than one base class.     C++ Multiple Inheritance Example In this example, two base classes Square and...

2 minutes read.

C++ User Defined Exceptions

Overriding and inheriting exception class capabilities may be used to define the new exception. Exception handling can also be used with classes. We may also make an exception for user-defined...

4 minutes read.

C++ Reading file

In file handling, read() function is used to read data from the file into the program. The read() uses ifstream library to read data from a file. Syntax file-stream-class   file-stream-object;   file-stream-object.read((char *)&var , sizeof (var)); <h3">Example ofstream  outfile;         outfile . read((char*)&emp,sizeof(emp)); C++ File Handling read() Function Example Reading the content of existing...

2 minutes read.

Default Constructor

C++ Default Constructor A default constructor is such constructor which does not take any parameter. A constructor initializes the data member when a class object created. If a programmer does not create any...

2 minutes read.

Pattern programs in C++

In this article, we are going to discuss different pattern programs in C++. Program for Printing * patterns: Right Angle Triangle* pattern #include <iostream> using namespace std; int main() {     int rows;     cout <<...

3 minutes read.

C++ Range-based For Loop

In C++ language, the range-based for loop was added, which is far superior than the ordinary For loop. The implementation of a range-based for loop doesn't really need much code. It's a...

4 minutes read.

Containership in C++

In C++, it is possible to create an object in one class into another class, and that object is a member of another class. This relationship is known as a...

4 minutes read.

Message Passing in C++

The act of sending and receiving information by an object is referred to as communication, and all communication between objects that takes place via message is known as message passing....

1 minute read.

Single level Inheritance

Inheritance is a fundamental element of C++’s Object-Oriented Programming (OOP). It allows a class (called the derived class) to inherit characteristics and attributes from another class (called the base class)....

5 minutes read.

Convex hull Algorithm in C++

The intersection of all convex sets containing a certain subset of a Euclidean space, or alternatively, the set of all convex combinations of points in the subset, defines the convex...

4 minutes read.

SDL library in C++ with Examples

SDL stands for Simple DirectMedia Layer. Using OpenGL and Direct3D, it is a cross-platform development library created to give users low-level access to audio, keyboard, mouse, joystick, and graphics hardware....

3 minutes read.

How to Reverse a String in C++ using 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 condition no longer...

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

Web Development in C++

Before learning above C++ web development, we need to learn about CGI What is CGI? CGI stands for common gateway interface. CGI is a standard that tells us how the exchange of...

4 minutes read.

Accumulate() and partial_sum() in C++ STL Numeric header

The C++ STL's numeric library includes the numeric header. This library provides efficient numeric arrays, support for random number generation, and fundamental mathematical operations and types. Several of the numeric...

3 minutes read.

How to create a library in C++

Before going on to the creation of a library, let’s understand its meaning. What is a library? In simple words, a library is a collection of numerous functions, methods, classes, header files...

7 minutes read.

Nullptr in C++

What is Nullptr in C++? A null pointer value is represented by the term nullptr. Use a null pointer value to indicate that a native pointer type, inner pointer, or object...

3 minutes read.

Reverse a String using Stack C/C++

Reverse the given string using stack. To turn "tutorialandexample" into "elpmaxednalairotut," for instance. Here is a straightforward stack-based technique for reversing strings. Algorithm: 1) Make a stack that is empty. 2) Push each character...

3 minutes read.