Skip to content
Related Articles

Related Articles

Comparison of Array and Pointers in C/C++ with Examples

Improve Article
Save Article
Like Article
  • Difficulty Level : Medium
  • Last Updated : 27 Dec, 2021

What is Array?

An array is the collection of multiple items of the same type stored contiguous memory locations. The position of each element can be calculated by adding an offset to the base value, i.e., the memory location of the first element of the array.

Syntax:

datatype var_name[size_of_array] = {elements};

Example:

C++




#include <iostream>
using namespace std;
int main()
{
    int i, j;
  
    // Declaring array
    int a[5];
  
    // Insert elements in array
    for (i = 0; i < 5; i++) 
    {
        a[i] = i + 1;
    }
  
    // Print elements of array
    for (j = 0; j < 5; j++) 
    {
        cout << a[j] << " ";
    }
    return 0;
}


Output

1 2 3 4 5 

Array

What is Pointer?

A pointer is the symbolic representation of addresses. It stores the address of variables or memory location. Pointers enable programmers to create and manipulate dynamic data structures. 

Syntax:

datatype *var_name;

Example:

C++




// C++ program to implement array
#include <iostream>
using namespace std;
  
// Driver code
int main()
{
    int a = 20;
    int* ptr;
    ptr = &a;
    cout << a << " " << ptr << 
            " " << *ptr;
    return 0;
}


Output

20 0x7ffe2ae2d4ec 20

Comparison of Array and Pointer

The pointer can be used to access the array elements, accessing the whole array using pointer arithmetic, makes the accessing faster. There are some other differences between an array and a pointer which are discussed below in the table.

S No. Array Pointer
1 type var_name[size]; type * var_name;
2 Collection of elements of similar data type.  Store the address of another variable.
3 The array can be initialized at the time of definition. Pointers cannot be initialized at definition.
4 An array can decide the number of elements it can store. The pointer can store the address of only one variable.
5 Arrays are allocated at compile time. Pointers are allocated at run-time.
6 Memory allocation is in sequence. Memory allocation is random.
7 Arrays are static in nature i.e. they cannot be resized according to the user requirements. Pointers are dynamic in nature i.e. memory allocated can be resized later.
8 An array of pointers can be generated. A pointer to an array can be generated.
9 Java Support the concept of an array. Java Does not support pointers.
10 An array is a group of elements. Python is not a group of elements.

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!