To use the elements of a heap allocated array, you use the subscript operator (square brackets) after the pointer that points to the array to specify the index of the element you wish to use. The index can be a literal or an expression that evaluates to an integer:
// Allocate an array of 3 integers - uninitialized
int* data = new int[3];
data[0] = 1; // set the first element to 1
data[1] = 2; // set the second element to 2
int location = 2;
data[location] = 3; // set the third element to 3
// print the first element
cout << "data[0]: " << data[0] << endl;
The [] syntax may look familiar. It is what we said NOT to use with vectors or strings. Vectors and strings are wrappers around dynamically allocated arrays. They provide [] to access the elements as if you were using a raw array. But usually you want to use at() instead, as it performs bounds checking and can help prevent accessing invalid memory.
Plain arrays do not provide a at() or any other way to access elements that will perform bounds checking. It is completely up to the programmer (with the help of other tools like AddressSanitizer) to avoid accessing invalid memory.
When you use the name of the pointer that points to the array, you are referring to the memory address of the array and not its contents. This means that expressions like data == other will not compare the contents of the arrays, but rather the memory addresses of the arrays. For example, in the memory diagram below, we see two different pointers, data and other, both pointing to arrays containing 1, 2, and 3. data == other would evaluate to false because it compares the pointers (the two memory addresses), not the things they point at.
This also means that something like int* copy = data; will not create a copy of the array, but rather another pointer to the same array. Given this code:
// Allocate an array of 3 integers - initialized to 1, 2, and 3
int* data = new int[3] {1, 2, 3};
int* copy = data; // copy points to the same array as data
There is really only one array, and both data and copy point to it. The assignment statement copied the memory address from data to copy. This is known as a shallow copy. If you modify the contents of the array using either pointer, the changes will be reflected when accessing the array through the other pointer.
To do something like compare two arrays, or to copy one array to another, you generally need to use a loop to work with each element one at a time. This Codelens demonstrates making a copy of an array using a loop:
The range-based for loop will not work on a dynamically allocated array. (There is no guarantee the compiler will know the size of the array.) You have to use a counting loop to iterate through the elements.
In this code, copy would be called a deep copy because it allocates its own memory and copies the contents of the original array into it. Once the copy is made, changing either array will not affect the other.