Pointer and Array In C++

Pointer vs Array :

A pointer is a type of variable that keeps as its value the memory address of another variable while an array is defined as the consecutive block of sequence which can store similar type of data.

Pointer vs Array2

Basic Definition

Array Example :

In the below program , we print all the elements on the screen.

Run
#include <iostream>
using namespace std;
int main ()
{
  int numbers[5] = { 17, 55, 76, 812, 735 };
  cout << "The numbers are: ";
for (const int &n:numbers)
    {
      cout << n << "  ";
    }
  cout << "\nThe numbers are: ";
  for (int i = 0; i < 5; ++i)
    {
      cout << numbers[i] << "  ";
    }
  return 0;
} 

Output :

The numbers are: 17  55  76  812  735  
The numbers are: 17  55  76  812  735  

Pointer Example :

Run
#include  <iostream> 
using namespace std;
int main()
{
    int var1 = 93;
    int var2 = 84;
    int var3 = 67;
    cout << "Address of var1: "<< &var1 << endl;
    cout << "Address of var2: " << &var2 << endl;
    cout << "Address of var3: " << &var3 << endl;
}

Output :

Address of var1: 0x7ffdbc9e38ec
Address of var2: 0x7ffdbc9e38f0
Address of var3: 0x7ffdbc9e38f4

Pointer vs Array :

Till now, we understand what the array and pointer is. Lets see some basic difference between pointer and array in C++.

PointersArrays
Value stored in the pointer can be changed.Array is a constant pointer
Pointer can’t be initialised at definitionArray can be initialised at definition.
Used to allocate static memoryUsed to allocate dynamic memory
Increment is valid in pointer e.g, ptr++;Increment is invalid in array e.g, a++;

Example :

In the below program, we access the elements of array using pointers.

Run
#include <iostream>  
using namespace std;
int main ()
{
  int arr[6] = { 21, 33, 65, 87, 59, 82 };
  printf ("Elements of array : ");
  for (int i = 0; i < 6; ++i)
    {
      printf ("%d ", *(arr + i));
    }
  return 0;
}

Output :

Elements of array : 21 33 65 87 59 82 

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription