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

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


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

WEBINAR:

On-Demand

Application Security Testing: An Integral Part of DevOps


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
Thanks for your registration, follow us on our social networks to keep up-to-date