Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: C++
Expertise: Advanced
Sep 6, 2005

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 <iostream>
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);
}
Sachin Kainth
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap