devxlogo

Arrays as Pointers in C++

Arrays as Pointers in C++

In C++, arrays and pointers are inextricably linked. The elements of an array are stored in consecutive memory addresses on the computer and the name of the array is equivalent to the address of the first element in it. Because of these facts, it’s easy to use pointers instead of subscripts to read and write the values of an array. To illustrate this point, consider the following program which copies the elements from one array into another and uses pointer notation throughout in place of subscripts:

#include "stdafx.h"#include using namespace std;void print (int* a, int* b, int arraySize) {   int* aPtr;   int* bPtr;   int i;   cout << "The values:" << endl;   for (i = 0, aPtr = a, bPtr = b; i < arraySize;       cout << "A[" << i << "]: " << *(aPtr++) << endl,       cout << "B[" << i << "]: " << *(bPtr++) << endl, i++);}int main() {   const int arraySize = 10;   int* a = new int[arraySize];   int* b = new int[arraySize];   int* aPtr;   int* bPtr;   int i;   // initialise   for (i = 0, aPtr = a, bPtr = b; i < arraySize; *(aPtr++) = 1, *(bPtr++) = 2, i++);   // print   print(a, b, arraySize);   // copy   for (i = 0, aPtr = a, bPtr = b; i < arraySize; *(aPtr++) = *(bPtr++), i++);   // print   print(a, b, arraySize);}
See also  Why ChatGPT Is So Important Today
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist