All about Arrays in C/C++ - Part I

Discussion in 'C++' started by Mridula, Oct 31, 2009.

  1. Mridula

    Mridula New Member

    Joined:
    Mar 5, 2008
    Messages:
    316
    Likes Received:
    19
    Trophy Points:
    0
    Occupation:
    S/w proffessional
    Location:
    Bangalore

    Introduction



    This article tries to cover all about Arrays like from it's definition till it's usage using a single dimension.

    Background



    Definition

    An array is a built-in Data Structure that holds a sequence of variables of same data type, that are stored in a contiguous memory locations.

    Some characteristics about Arrays

    • The elements of an array are indiced and accessed by their index, where as first position/index of an array starts from "0" and last position is sizeOfArray-1 !!
    • By default, Arrays are not initialised.
    • Like any other variable, an array must be declared before it is used.
    • Each element in an Array must be printed individually.
    • An Array cannot be copied/assigned/compared from another Array directly, these operations have to be done element by element basis.
    • Name of the Array is nothing but address of/pointer to the first element of the Array
    • There is no Array bound checking done in C. Trying to access the position at sizeofArray or beyond that is an Error and results in an undefined behaviour.
    • ArrayName indicates the base address or address of the first element in the Array.
    • Address of any element in a Single Dimensional Array can be caclulated as
      ElementAddress = BaseAddress+ indexOfTheElement * SizeOfTheElement

    Declaration of an Array

    Declaration of an array takes data_type of the elements to be stored, variable name followed by the size of the array wrapped within square brackets as below:

    data_type variableNameOfArray[no_elements]

    For Example:

    int employee[5] = {10,20,30,40,50};

    [​IMG]

    where employee is the name of a single dimensional array variable, that can hold 5 variables of integer type. So, the number 5 indicates the size of the array employee.
    Where "0", "1", "2", "3", "4" shows the indices of the array employee. Any element of an Array, can be accessed by using it's respective index inside [] as below:

    printf("%d", employee[2]);

    This will access and print the 3rd element i.e. 30 of the Array employee.


    Array Initialization

    We can Initilize an Array when it is declared. Initializers are constant values/expressions seperated by a comma and enclosed within flower braces {} as below:

    dataType variableNameOfArray[no_elements] = {values}


    int employee[5] = {120, 121, 122, 123, 124};

    As a convinience, if you leave out the size of the array, it creates it with the exact size to hold that number of initial values.


    int employee[] = {120, 121, 122, 123, 124};

    The elements in the aggregate that are not given initilizers are default initialized according to their data type.

    The code



    Code:
    #include<iostream.h>
    
    int main()
    {
      int array[5]={1,2};
      unsigned i;
    
      cout<<"\nInitilization of rest of the elements\n";
      for(i=0; i<5; ++i)
      {
        cout<<"Array["<<i<<"]"<<array[i]<<endl;
      }
    }
    
    Output:
    Initilization of rest of the elements
    Array[0]1
    Array[1]2
    Array[2]0
    Array[3]0
    Array[4]0
    In this code, only the array index 0 and 1 are initilized with values 1 & 2, whereas rest of the elements in the array will be initilized with zeros.

    Also, We can initialize all the elements of an integer Array with 0 value by assigning with empty {} as below:

    int array[5] = {};


    Array Initilization in a class

    Arrays are always initilized outside the class. Usually static const data types are initilized inside the class declaration, but, static const Arrays are also initilized outside the class declaration as below:

    The code



    Code:
    #include<iostream.h>
    
    class Abc{
      static const int arr[3];
      static const double var = 3.14;
    
      public: Abc()
              { 
                for(int i=0; i<3; ++i)
                {
                  printf("%d", arr[i]);
                }
              }
    };
    
    const int Abc::arr[3] = {1,2,3};
    
    int main()
    {
      Abc aa;
    
      return(0);
    }
    
    Output
    123
    

    Size of an Array

    Irrespective of whether an Array is initialized or not, the size of an Array is nothing but ;
    sizeOf(dataType of the element) * arraySize.

    The code



    Code:
    #include<iostream.h>
    
    int main()
    {
      int arr[5];
    
      cout<<"\nBy default array elements are not initilized\n";
      for(int i=0; i<5; ++i)
      {
        cout<<"arr["<<i<<"]="<<arr[i]<<endl;
      }
      cout<<endl;
      
      cout<<"Size of this array \"arr\" is: "<<sizeof(arr)<<endl;
      
      return(0);
    }
    
    Output:
    By default array elements are not initilized
    arr[0]=-4265576
    arr[1]=163864
    arr[2]=3
    arr[3]=-4265476
    arr[4]=4
    
    Size of this array "arr" is: 20
    
    The above code also confirms that by default array elements are not initilized.


    Arrays and References

    We cannot have an Array of references. Whereas we can have an Reference to an Array as an argument to a function.

    The code



    Code:
    #include<iostream.h>
    
    void print(int (&arr)[3])
    {
      for(int i=0; i<3; ++i)
      {
        cout<<arr[i]<<endl;
      }
    }
    
    int main()
    {
      int array[3]={1,2,3};
      print(array);
    
      return(0);
    }
    
    Output:
    1
    2
    3
    

    Pointer Arithmetic and Arrays

    Address to a first element of an Array is nothing but Array name itself and it is a pointer of it's element type or Array type. Adding 1 to this pointer, gives the address of the next element in the Array. It means, it adds with 1*sizeOf(elementDataType) to the base address of the array.

    For Example:

    Code:
    int array[3] = {10,20,30};
    cout<<"*(array+1)"<<*(array+1)<<endl;
    
    Results the content of second element i.e. "20". array+1 adds (1*4) to the base address i.e. array and gives the content of that address. Where 4 is size of an int nothing but size of an element of array here!!

    In other way we can say

    array or array+0 ----> &array[0]

    *array -----> array[0]


    And

    array+1 ------> &array[1]
    *(array+1) -----> array[1]

    .
    .
    .

    array+i --------> & array
    *(array+i) ------> array


    Same way, we can as well do subtraction here.

    By seeing these examples, we can say that array behaves like a pointer, but really it is not. As we cannot assign values to it as below:

    Code:
    int arr[5];
    int j;
    arr = &j // gives complation error!!
    
    But however we can assign an array name to a pointer as below:

    Code:
    int arr[5];
    int *p = arr; or
    p = &arr[0]
    

    Static and Dynamic Array allocation

    int employee[5];

    When an Array is declared like above, the memory is allocated for all the elements of it and it will be there till the life time of the program. This is called as Static Array allocation. So, here the developer knows in advance the size of the Array at compile time itself.

    In case, if the developer does not know the Array size at compile time, then Array can be alllocaed at run time as well. This is called as Dynamic Allocation of an Array.

    For Example:

    The code



    Code:
    #include<iostream.h>
    
    int main()
    {
      int *arr;
      int size, i;
      
      cout<<"\nEnter the Array size:\n";
      cin>>size;
    
      cout<<"\nEnter Array elements\n";
      for(i=0; i<size; ++i)
      {
        cin>>arr[i];
      }
    
      cout<<"\nPrinting the Array elements\n";
      for(i=0; i<size; ++i)
      {
        cout<<"arr["<<i<<"]="<<arr[i]<<endl;
      }
    
      return(0);
    }
    
    Output:
    
    ./a.out
    
    Enter the Array size:
    3
    
    Enter Array elements
    20
    30
    40
    
    Printing the Array elements
    arr[0]=20
    arr[1]=30
    arr[2]=40
    

    Arrays of Characters

    Arrays of characters are special, as we can Initialize the Array using string literals as below:

    char array[8]= {'M', 'r', 'i', 'd', 'u', 'l', 'a'}
    char array[8]= "Mridula";


    Here we can see that Mridula can be Initized as a string !!

    Also, if some of the elements in character Arrays are not given initizers, then they will be initilized with NULL or '\0' character.As like initeger Arrays, character arrays are also can be initilized with NULL character just by assigning them with {} as below.

    char array[8] = {};

    Otherwise, by Default, it will be initilized with some junk characters.


    Array as an Argument to a function

    A function can receive Array as an argument with any of the below forms:

    1. As a pointer to an Array like int func(int *array);
    2. As a sized Array like int func(int array[3]);
    3. As an unsized Array like int func( int array[]);
    4. As a reference to an Array like void func(int (&arr)[3]);

    But always an array name that as a function argument is converted to a pointer to the start of array, at compile time itself, by the compiler. So any reference to that array inside the function is treated as a pointer reference.

    For Example:

    Code:
    int array1[50];
    
    void fun(int arr2[])
    {
      arr2[1] = 3;
      *arr2 = 3;
      arr2 = array1;
      
    }
    
    
    int main()
    {
    int arr2[3];
    
    arr2[1] = 3;
    *arr2 = 3;
    
    //we cannot do the below
    //arr2 = array1;
    
    return(0);
    }
    
    If we see the above code snippets, array when it is passed as an argument to a function, can be assigned to another array as it is treated always as a pointer. Whereas we cannot do the same in main function, it would give compilation error, as we are trying to change the array name itself, which cannot be done.

    Also

    Code:
    void func(int [] a) 
    {
     return sizeof (a); // returns the size of the pointer p not the size of the array !!
    }
    
    int main()
    {
     int num[2];
     cout << sizeof (num); //Returns the size of the array num!!
     func(num);
    }
    
    The above code snippet confirms that array which is passed to as an argument to function, is treated as a pointer inside the function as the sizeof that argument results with sizeof a pointer and not sizeof the Array.

    Also, by giving/sending a pointer to any intermediate element of an Array to a function, we can just pass the slice/last part of the array from that intermediate point.

    For Example:

    The code



    Code:
    #include<iostream.h>
    
    void func(int *arr)
    {
      int i;
      
      for (i=0; i<2; ++i)
      {
        cout<<arr[i]<<endl;
      }
    }
    
    int main()
    {
      int array[4] = {100,200,300,400};
      cout<<"Sending slice of an array...\n";
    
      int * ptr = &array[2];
      func(ptr);
      
      return(0);
    }
    Output:
    
    ./a.out
    Sending slice of an array...
    300
    400
    
    Here ptr which is pointing to 2nd index of the array[4] is sent to func and so only 2nd and 3rd indices has been printed on accessing the array through ptr in function func.


    Operations Done on Arrays

    • Storing/Collecting elements of same data type.
    • Iterating through all the elements in an Array
    • Searching an element in an Array
    • Comparision of two Arrays
    • Assignment operation

    The bottom line: Arrays are nothing but collection of elements of same Data Type, having same identifer as Array name itself !!.
     
    Last edited by a moderator: Jan 21, 2017
  2. Karpov2007

    Karpov2007 Banned

    Joined:
    Oct 14, 2007
    Messages:
    66
    Likes Received:
    2
    Trophy Points:
    0
    Occupation:
    scientific adviser of OOO "Program Verification Sy
    Location:
    Russia, Tula
    Home Page:
    http://www.viva64.com/
    azmatdear likes this.
  3. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
  4. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
  5. rasd123

    rasd123 Banned

    Joined:
    Nov 4, 2009
    Messages:
    40
    Likes Received:
    0
    Trophy Points:
    0
    Thanks to share this information.
     
  6. technica

    technica New Member

    Joined:
    Dec 15, 2007
    Messages:
    107
    Likes Received:
    0
    Trophy Points:
    0
    Home Page:
    http://www.technicaltalk.net
    Both your articles Part I and Part II on this topic are real good. They will surly help lot looking for help and understanding arrays.
     
  7. Mridula

    Mridula New Member

    Joined:
    Mar 5, 2008
    Messages:
    316
    Likes Received:
    19
    Trophy Points:
    0
    Occupation:
    S/w proffessional
    Location:
    Bangalore
    many thanks!!
     
  8. rasd123

    rasd123 Banned

    Joined:
    Nov 4, 2009
    Messages:
    40
    Likes Received:
    0
    Trophy Points:
    0
    Thankiossk Cool!
     
  9. sathi

    sathi New Member

    Joined:
    Nov 23, 2009
    Messages:
    3
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    current job is student in karpagam
    Location:
    coimbatore
    its amazing ,but i don't understanding about arrays. i'am begineer..how can i easily understand about arrays..reply must anybody..i'am very curiosity know about c++..
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice