------------------------------------------------------------------------------
MC logo
Arrays and Pointers
[^] CSc 220 Home
------------------------------------------------------------------------------
[Introduction] [Boolean and Control] [Functions] [Arrays and Pointers] [Dynamic Arrays] [Array Errors] [Command Array] [Standard Containers] [Structs and Classes] [Automatic Pointer] [Multi-File Programs] [Copying Objects] [Templates] [Inheritance] [Plain C I/O] [Type Odds And Ends] [Plain C Strings] [File I/O]
[Array Echo] [Basic Pointers] [Swap Using Pointers] [Arrays and Pointers] [Array Passing] [Integer Select Sort] [Integer Quick Sort] [Integer Library Sort] [Pointers and References]
arrptr.cpp
#include <iostream>
#include <iomanip>
using namespace std;

main()
{
        int fred[] = { 10, 20, 30, 40, 50, 60, 70 };
        int *joe = fred + 5;
        int *alex = joe - 3;

        fred[0] = 99;
        joe[0] = 199;
        alex[1] = 299;

        int m;
        for(m = 0; m < 7; m++) cout << setw(4) << m;
        cout << endl;
        for(m = 0; m < 7; m++) cout << setw(4) << fred[m];
        cout << endl;
}

Note that we have created the array fred with an initial value:
int fred[] = { 10, 20, 30, 40, 50, 60, 70 };
Though the [] symbol is common in Java, this is one of only three places in C++ where you can give the [] without putting a size inside. The compiler takes the size of the array from the size of the initializer. We could also have said:
int fred[7] = { 10, 20, 30, 40, 50, 60, 70 };
which would have been redundant. We could have said:
int fred[10] = { 10, 20, 30, 40, 50, 60, 70 };
which allows for extra space. This fills the first seven positions with the given values, and the remaining three with zeros. In fact, a nice trick to get an array initialized to zero, is to say something like:
int fred[100] = { };
Which gives a hundred positions in fred, and sets them all to zero.

We could also have said

int fred[5] = { 10, 20, 30, 40, 50, 60, 70 };
but that would have produced a compile error, since the initializer won't fit in five positions.

Oh, the other two places are declaring an array parameter and in the delete operator.