Saturday, 1 June, 2019 UTC


Summary

C++ Pointers Tutorial | Pointers in C/C++ with Examples is today’s topic. A pointer is a variable whose value is the address of another variable. Pointers are a symbolic representation of addresses. They enable programs to simulate call-by-reference as well as to create and manipulate dynamic data structures. You must declare the pointer before you can work with it.
C++ Pointers Tutorial
If we want to understand the pointer, let’s review the “regular” variables first. If you’re familiar with the programming language without pointers like JavaScript, this is what you think when you hear “variable”.
When declaring a variable by an identifier (or name), the variable is synonymous with its value.
int number = 3;
std::cout << "number is initialized with a value of " << number << "\n";
// Outputs: number is initialized with a value of 3
The value of a variable can be modified directly.
number++;
number = number * 2;
std::cout << "After modifying number, its value is now " << number << "\n";
// Outputs: After modifying number, its value is now 8
Every value lives at memory addresses. The memory address of a variable can be accessed using the & operator.
std::cout << "The number variable's value lives at memory address " << &number << "\n";

Address-of operator (&)

The address of the variable can be obtained by preceding the name of a variable with an ampersand sign (&), known as an address-of operator. See the following code.
app = &var;
This would assign the address of a variable var to an app; by preceding the name of the variable var with the address-of operator (&), we are no longer assigning the content of the variable itself to an app, but its address.
The actual address of the variable in memory cannot be known before runtime, but let’s assume, to help clarify some concepts, that var is placed during runtime in the memory address 1921.
What are the Pointers?
As the name suggests, pointers are a different kind of entities compared to standard variables because it stores the address of some other variable or in a waypoint to a variable.
Ex.  int a; // ‘a’ is a variable that will hold some integer value.
       int *a; // ‘a’ is a pointer to a integer variable.
 

General Declaration

<type> * pointerName;    <type> can be int, float, char, etc.
Why use pointers?
As mentioned earlier pointers hold the address, so we can use it to reduce complexity while sending parameters in the function. Suppose there is an array of enormous size and we have to send the array as a parameter of the function, So instead of passing the array we can pass the address of the first variable.
Also, computing operations using pointers that are at address level are less complicated than without it.
Sample Example:
To know the address of variable we use the referencing operator ‘&’ and to see the value stored at the address pointed by a pointer we use dereferencing operator ‘*’.
int a = 10;  // integer variable a
int *p = &a;  // referencing operator ‘&’ prefixed with integer variable a. p will now store the address of a.
int b = *p; // dereferencing pointer p using ‘*’ prefixed with p. b will store the value of a that is 10.
See the following pointer program in C++.
#include <iostream>  
using namespace std;  
  
int main()  
{  
    // Sample program to show pointers concepts.  
    int a=20; // integer variable a  
    int * p; // pointer to an integer  
    p = &a;  // p now holds address of a.  
  
    cout << "Address of a : " << p << "\n";  
  
    int b = *p;  // dereferencing using *, now b has the same value as a.  
    cout << "Value of a: " << *p << "\n";  
  
    return 0;  
}  
See the output.
 

Applications:

Used in calling by reference using pointers
In call by reference when a variable is passed as a reference then changes made to it inside the function body is also reflected in the main function. Consider the below program of swapping of two numbers using pointers.
#include <iostream>  
using namespace std;  
  
void swap_(int *x, int *y)  
{  
    int temp= *x; // store the value stored at address pointed by x.  
    *x = *y;      // change value at address pointed by x to value at address y  
    *y = temp;   // change value at address pointed by y to value that was present at address of x at start.  
}  
int main()  
{  
    // Sample program to show call by reference by pointers  
    int a=20; // integer variable a  
    int b=30; // integer variable b  
    cout << "Before swapping : " << a << " " << b << "\n";  
    swap_(&a,&b); // swap function  
  
    cout << "After swapping : " << a << " " << b << "\n";  
    return 0;  
}
After swap function is called values are swapped between a & b that is a=30 and b=20. See the output.
 
Array of Pointers
An array of pointers mean that there is an array that stores addresses of a different variable.
int * a[10];  // array of integer pointers
See the following code example.
#include <iostream>  
using namespace std;  
  
int main()  
{  
    // Sample program to show call by reference by pointers  
    int a[10];  
    int i,j;  
    for(i=0;i<10;i++)  
        a[i]=i+1;  
    cout << "Without pointers :\n";  
    for(i=0;i<10;i++)  
        cout << a[i] << " ";  
    cout << "\n";  
    int *p[10]; // pointers to each member of array of a  
  
    for(i=0;i<10;i++)  
        p[i] = &a[i];  
  
    cout << "Using pointers :\n";  
    for(i=0;i<10;i++)  
        cout << *p[i] << " ";  
  
  
    return 0;  
}
See the output.
 
Pointers and Array
Name of the array is the starting address of the array. So, consider int a[10]; a , &a , &a[0] signify the same thing.
To access ith index in the array it can be done using *(a+i), *(i+a) , a[i] or i[a]. All are same.
See the following code example.
#include <iostream>
using namespace std;

int main()
{
    // Sample program to show call by reference by pointers
    int a[10];
    int i,j;
    for(i=0;i<10;i++)
        a[i]=i+1;
    //All point to the same address
    cout << a << " " << &a << " " << &a[0] << "\n" ;
    // All give the same value that is the value contained at a[1]
    cout << *(a+1) << " " << *(1+a) << " " << a[1] << " " << 1[a] <<"\n";


    return 0;
}
See the following output.
 
Pointers Arithmetic
Arithmetic operations like ++, –, + , – can be operated on pointer variables.
Consider, int a[3] = {1,2,3};
ptr = &a[0];

ptr = ptr+1; // This will point to the next variable in the array. ptr++ will do the same thing.

Ptr = ptr-1; // Again the pointer will point to the 0th index. ptr—will do the same thing.
See the following code.
#include <iostream>  
using namespace std;  
  
  
int main()  
{  
    // Sample program to show call by reference by pointers  
    int a[3] = {1,2,3};  
    int * p= &a[0];  
    p=p+1; // point to next integer  
  
    cout << "Value of 2nd element : " << *p << "\n";  
  
    p--;  
    cout << "Value of 1st element : " << *p << "\n";  
  
    return 0;  
}  
See the output.
 
Some essential types of pointers are following.

Null pointer

The pointer which points to nothing and has been initialized to NULL. A NULL pointer is a value. Value is 0.
 
See the following code.
#include <iostream>
using namespace std;

int main()
{
    // Sample program to show Null pointer
    int * p = NULL; // initialized to NULL

    cout << "VALUE : " << p << "\n";

    return 0;
}
See the output.
 

Void Pointer

Unlike null pointer it is not a value, it is instead a type of pointer. Typecasting needs to be
used while dealing with void pointers. Means, using this pointer, you can efficiently work with any datatype. You need to include that datatype.
See the following program.
#include <iostream>
using namespace std;

int main()
{
    // Sample program to show Void pointer
    int a=10;
    void * p; // initialized to NULL

    p = &a;  // address of a

    cout << "VALUE : " << *((int*)p) << "\n"; // typecasting used otherwise there will be error. 

    return 0;
}
See the output.
 
Dangling pointer
A pointer which points to a memory location which no longer exists that is the memory location has been deleted. See the following program.
#include <iostream>
using namespace std;

int main()
{
    // Sample program to show dangling pointer
    int *a = new int[2];
    a[0] = 10;
    a[1] = 20;
    int *p = &a[0];
    delete a;    // comment this line to avoid dangling pointer

    cout <<"Value is: "<<*p<<"\n";  // Garbage value will be printed 
    return 0;
}
See the following output.
 
Pointer to pointer
A pointer that stores the address of another pointer is called a pointer to pointer. Here, in this case, what happens is, a pointer store the address of another pointer, and then that 2nd pointer stores the address of one variable.
 
Below program tells how to deal with it.
#include <iostream>  
using namespace std;  
  
int main()  
{  
    // Sample program to show  pointer to pointer  
    int a = 10;  
    int *p = &a; // stores the address of integer a  
    int **q = &p; // stores the address of pointer p  
  
    cout << "Address of a : " << p << "\n";  
    cout << "Address of p : " << q << "\n";  
  
    cout << "Value of p : " << p << " " << *q << "\n" ; // All are same  
  
    cout << "Value of a : " << a << " " << *p << " " << **q << "\n"; // All are same  
  
    return 0;  
}
See the output.
 
Finally, C++ Pointers Tutorial | Pointers in C/C++ with Examples article is over.
The post C++ Pointers Tutorial | Pointers in C/C++ with Examples appeared first on AppDividend.