Arrays in c++ Language

Arrays in c++ Language

C++ is an object-oriented programming language, and a vector is an example of a software object. C++ began as an extension of the C programming language, but C does not directly support object-oriented programming. Consequently, C does not have vectors available to represent sequence types. The C language uses a more primitive construct called an array. True to its C roots, C++ supports arrays as well as vectors. Some C++ libraries use arrays in instead of vectors.

Static Array

Arrays come in two varieties, static and dynamic. A programmer must supply the size of a static array when declaring it; for example, the following statement:

// list is an array of 25 integers
int list[25];

declares list to be an array of 25 integers. The value within the square brackets specifies the number of elements in the array, and the size is fixed for the life of the array. The value within the square brackets must be a constant value determined at compile time

int x;
std::cin >> x; // Get x's value from the user at run time
int list_1[x]; // Illegal for a static array
std::vector<int> list_2(x); // OK for a vector

It is possible to declare an array and initialize it with a sequence of elements, with a syntax similar to that of vectors:

double collection[] = { 1.0, 3.5, 0.5, 7.2 };

The compiler can count the elements in the list, so you need not supply a number within the square brackets. If you provide a number within the square brackets, it should be at least as large as the number of elements in the initialization list.

int arr[100];

As with vectors, once we declare an array, we can access its elements using the square bracket operator:

int list[3]; // Declare list to be an array of three ints
list[0] = 5 ; // Make the first element 5
list[1] = -3 ; // Make the second element -3
list[2] = 12 ; // Make the last element 12
#include <iostream>

/*
 * print(a, n)
 * Prints the contents of an int array
 * a is the array to print
 * n is the size of the array
 */
void print(int a[], int n) {
    for (int i = 0; i < n; i++)
        std::cout << a[i] << " ";
    std::cout << '\n';
}
/*
 * sum(a, n)
 * Adds up the contents of an int array
 * a is the array to sum
 * n is the size of the array
 */
int sum(int a[], int n) {
    int result = 0;
    for (int i = 0; i < n; i++)
        result += a[i];
    return result;
}
int main() {
    int list[] = {
        2,
        4,
        6,
        8
    };
    // Print the contents of the array
    print(list, 4);
    // Compute and display sum
    std::cout << sum(list, 4) << '\n';
    // Zero out all the elements of list
    for (int i = 0; i < 4; i++)
        list[i] = 0;
    // Reprint the contents of the array
    print(list, 4);
    // Compute and display sum
    std::cout << sum(list, 4) << '\n';
}
#include <iostream>

/*
 * print(a, n)
 * Prints the contents of an int array
 * a is the array to print
 * n is the size of the array
 */
void print(int a[], int n) {
    for (int i = 0; i < n; i++)
        std::cout << a[i] << " ";
    std::cout << '\n';
}
/*
 * clear(a, n)
 * Makes all the elements of array a zero
 * a is the array to zero out
 * n is the size of the array
 */
void clear(int a[], int n) {
    for (int i = 0; i < n; i++)
        a[i] = 0;
}
int main() {
    int list[] = {
        2,
        4,
        6,
        8
    };
    // Print the contents of the array
    print(list, 4);
    // Zero out the array
    clear(list, 4);
    // Reprint the contents of the array
    print(list, 4);
}

Pointers and Arrays

An array name used in C++ source code references a location in memory, the address of the first element (element at index 0) in the array. In this way an array name is similar to a constant pointer (see Section 10.7 for more information about C++ pointers).

#include <iostream>

int main() {
    int a[] = {
            2,
            4,
            6,
            8,
            10,
            12,
            14,
            16,
            18,
            20
        },
        * p;
    p = & a[0]; // p points to first element of array a
    // Print out the contents of the array
    for (int i = 0; i < 10; i++) {
        std::cout << * p << ' '; // Print the element p points to
        p++; // Increment p so it points to the next element
    }
    std::cout << '\n';
}
#include <iostream>

int main() {
    int a[] = {
            2,
            4,
            6,
            8,
            10,
            12,
            14,
            16,
            18,
            20
        },
        * begin, * end, * cursor;
    begin = a; // begin points to the first element of array a
    end = a + 10; // end points to just after the last element
    // Print out the contents of the array
    cursor = begin;
    while (cursor != end) {
        std::cout << * cursor << ' '; // Print the element
        cursor++; // Increment cursor so it points to the next element
    }
    std::cout << '\n';
}
#include <iostream>

int main() {
    // Make an array
    int arr[] = {
        10,
        20,
        30,
        40,
        50
    };
    int * p = arr; // p points to the first element
    std::cout << * p << '\n'; // Prints 10, does not change p
    std::cout << p[0] << '\n'; // Prints 10, does not change p
    std::cout << p[1] << '\n'; // Prints 20, does not change p
    std::cout << * p << '\n'; // Prints 10, does not change p
    p++; // Advances p to the next element
    std::cout << * p << '\n'; // Prints 20, does not change p
    p += 2; // Advance p two places
    std::cout << * p << '\n'; // Prints 40, does not change p
    std::cout << p[0] << '\n'; // Prints 40, does not change p
    std::cout << p[1] << '\n'; // Prints 50, does not change p
    p--; // Moves p back one place
    std::cout << * p << '\n'; // Prints 30, does not change p
}
10
10
20
10
20
40
40
50
30

Dynamic Arrays

Programmers need not worry about managing the memory used by static arrays. The compiler and run-time environment automatically ensure the array has enough space to hold all of its elements. The space held by local arrays is freed up automatically when the local array goes out of the scope of its declaration. Global arrays live for the lifetime of the executing program.

Comparing static arrays, dynamic arrays, and vectors
Comparing static arrays, dynamic arrays, and vectors
#include <iostream>
 // Maximum number of expected values is 1,000,000
const int MAX_NUMBER_OF_ENTRIES = 1000000;
double numbers[MAX_NUMBER_OF_ENTRIES];
int main() {
    double sum = 0.0;
    int size; // Actual number of entries
    // Get effective size of the array
    std::cout << "Please enter number of values to process: ";
    std::cin >> size;
    if (size > 0) { // Nothing to do with no entries
        std::cout << "Please enter " << size << " numbers: ";
        // Allow the user to enter in the values.
        for (int i = 0; i < size; i++) {
            std::cin >> numbers[i];
            sum += numbers[i];
        }
        std::cout << "The average of ";
        for (int i = 0; i < size - 1; i++)
            std::cout << numbers[i] << ", ";
        // No comma following last element
        std::cout << numbers[size - 1] << " is " <<
            sum / size << '\n';
    }
}

An executing program automatically allocates on the stack the local variables of a function when a caller invokes the function. The executing program also automatically local variables when the function returns. The programmer does not need to explicitly manage local variables. Dynamically allocated memory, however, requires more attention on the part of the programmer.