Learn Arrays in C and C++ [With Examples]

An exhibit in C/C++ or be it in any programming language is an assortment of comparable information things put away at coterminous memory areas and components can be gotten to haphazardly utilizing lists of a cluster. They can be utilized to store assortment of crude information types, for example, int, float, twofold, burn, and so on of a specific sort. To add to it, an exhibit in C/C++ can store determined information types, for example, the constructions, pointers and so on Given beneath is the image portrayal of a cluster.

Learn Arrays in C and C++

We can utilize ordinary factors (v1, v2, v3, ..) when we have few items, yet to store an enormous number of occasions, it becomes hard to oversee them with typical factors. The possibility of an exhibit is to address many cases in a single variable.

Exhibit statement in C/C++:

Note: In above picture int a[3]={[0… 1]=3}; this sort of affirmation has been old since GCC 2.5

There are different manners by which we can proclaim a cluster. It tends to be finished by indicating its sort and size, by instating it or both.

Array declaration by specifying the size

// Array declaration by specifying size
int arr1[10];
 
// With recent C/C++ versions, we can also
// declare an array of user specified size
int n = 10;
int arr2[n];

Array declaration by initializing elements

// Array declaration by initializing elements
int arr[] = { 10, 20, 30, 40 }
 
// Compiler creates an array of size 4.
// above is same as  "int arr[4] = {10, 20, 30, 40}"

Array declaration by specifying size and initializing elements

// Array declaration by specifying size and initializing
// elements
int arr[6] = { 10, 20, 30, 40 }
 
// Compiler creates an array of size 6, initializes first
// 4 elements as specified by user and rest two elements as
// 0. above is same as  "int arr[] = {10, 20, 30, 40, 0, 0}"

Benefits of an Array in C/C++:

  • Arbitrary access of components utilizing exhibit record.
  • Utilization of less line of code as it makes a solitary exhibit of various components.
  • Simple admittance to every one of the components.
  • Crossing through the cluster turns out to be simple utilizing a solitary circle.
  • Arranging turns out to be simple as it very well may be refined by composing less line of code.

Hindrances of an Array in C/C++:

  • Permits a decent number of components to be entered which is chosen at the hour of announcement. Not at all like a connected rundown, a cluster in C isn’t dynamic.
  • Inclusion and erasure of components can be exorbitant since the components are should have been overseen as per the new memory assignment.

Realities about Array in C/C++:

Getting to Array Elements:

Cluster components are gotten to by utilizing a number list. Exhibit record begins with 0 and goes till size of cluster less 1.
Name of the exhibit is additionally a pointer to the primary component of cluster.

Model:

#include <stdio.h>
 
int main()
{
    int arr[5];
    arr[0] = 5;
    arr[2] = -10;
    arr[3 / 2] = 2; // this is same as arr[1] = 2
    arr[3] = arr[0];
 
    printf("%d %d %d %d", arr[0], 
           arr[1], arr[2], arr[3]);
 
    return 0;
}

Output

5 2 -10 5

No Index Out of bound Checking:

There is no index out of bounds checking in C/C++, for example, the following program compiles fine but may produce unexpected output when run.

// This C program compiles fine
// as index out of bound
// is not checked in C.
 
#include <stdio.h>
 
int main()
{
    int arr[2];
 
    printf("%d ", arr[3]);
    printf("%d ", arr[-2]);
 
    return 0;
}
Output
-449684907 4195777

In C, it is not a compiler error to initialize an array with more elements than the specified size. For example, the below program compiles fine and shows just Warning.

#include <stdio.h>
int main()
{
 
    // Array declaration by initializing it 
    // with more elements than specified size.
    int arr[2] = { 10, 20, 30, 40, 50 };
 
    return 0;
}

Warnings:

prog.c: In function 'main':
prog.c:7:25: warning: excess elements in array initializer
  int arr[2] = { 10, 20, 30, 40, 50 };
                         ^
prog.c:7:25: note: (near initialization for 'arr')
prog.c:7:29: warning: excess elements in array initializer
  int arr[2] = { 10, 20, 30, 40, 50 };
                             ^
prog.c:7:29: note: (near initialization for 'arr')
prog.c:7:33: warning: excess elements in array initializer
  int arr[2] = { 10, 20, 30, 40, 50 };
                                 ^
prog.c:7:33: note: (near initialization for 'arr')
  • Note: The program won’t compile in C++. If we save the above program as a .cpp, the program generates compiler error “error: too many initializers for ‘int [2]’”.

Example:

// C program to demonstrate that
// array elements are stored
// contiguous locations
 
#include <stdio.h>
int main()
{
    // an array of 10 integers.  
    // If arr[0] is stored at
    // address x, then arr[1] is
    // stored at x + sizeof(int)
    // arr[2] is stored at x + 
    // sizeof(int) + sizeof(int)
    // and so on.
    int arr[5], i;
 
    printf("Size of integer in this compiler is %lu\n",
           sizeof(int));
 
    for (i = 0; i < 5; i++)
        // The use of '&' before a variable name, yields
        // address of variable.
        printf("Address arr[%d] is %p\n", i, &arr[i]);
 
    return 0;
}
Output

Size of integer in this compiler is 4
Address arr[0] is 0x7ffe75c32210
Address arr[1] is 0x7ffe75c32214
Address arr[2] is 0x7ffe75c32218
Address arr[3] is 0x7ffe75c3221c
Address arr[4] is 0x7ffe75c32220

Another way to traverse the array

#include<bits/stdc++.h>
using namespace std;
 
int main()
{
    int arr[6]={11,12,13,14,15,16};
    // Way -1
    for(int i=0;i<6;i++)
        cout<<arr[i]<<" ";
   
  cout<<endl;
      // Way 2
    cout<<"By Other Method:"<<endl;
    for(int i=0;i<6;i++)   
        cout<<i[arr]<<" ";
   
    cout<<endl;
 
    return 0;
}
 
// Contributed by Akshay Pawar ( Username - akshaypawar4)
Output

11 12 13 14 15 16 
By Other Method:
11 12 13 14 15 16

Array versus Pointers

Arrays and pointers are two unique things (we can check by applying sizeof). The disarray happens in light of the fact that cluster name shows the location of first component and exhibits are taken a break as pointers (regardless of whether we utilize square section). If it’s not too much trouble, see Difference among pointer and exhibit in C? for additional subtleties.

What is vector in C++?

A vector in C++ is a class in STL that addresses an exhibit. The upsides of vector over typical exhibits are,

  • We needn’t bother with pass size as an additional a boundary when we announce a vector i.e, Vectors support dynamic sizes (we don’t need to at first determine size of a vector). We can likewise resize a vector.
  • Vectors have many in-constructed capacities like, eliminating a component, and so on
  • To find out about functionalities given by vector, kindly allude vector in C++ for additional subtleties.

Also ReadHow to Split a String in Golang?

Leave a Reply

Your email address will not be published. Required fields are marked *