Some applications of pointers in c++

Pointers in C++ can be useful in doing various things like modifying variables of a function in another function by passing down the arguments as addresses of variables we want to modify, and then accessing them via pointers. Its also used widely for dynamic memory allocation, such as in linked lists.

When accessing arrays, behind the scenes arr[2] gets converted to *(arr+2), meaning skip two positions ahead of the base address to get the value stored at the 3rd place.

void swap(int* x, int* y)
{
    int temp = *x;
    *x = *y;
    *y = temp;
}
 
int main()
{
    int arr[] = {100,20,3,4};

    cout<<arr[2]<<endl;
    cout<<*(arr+2);
    return 0;
}

Post a Comment

0 Comments