Dynamically allocated arrays

Submitted by:Tim Kelly

Date added:06 August, 2012

Category:C++

Showing how to work with dynamically allocated arrays

Tags: dynamically arrays , allocated arrays

Code Snippet:

#include <iostream>
using namespace std;
int main() {
// (recalling static arrays)
// declare static array
int arr[3] = {1, 2, 3};
// print values stored in arr
for (int i = 0; i < 3; i++)
cout << "arr[" << i << "]: " << arr[i] << endl;
cout << endl;
// declare pointer to int
int *pArr;
// allocate memory for three integers
pArr = new int[3];
// assign values using square brackets []
pArr[0] = 1;
pArr[1] = 2;
pArr[2] = 3;
// three ways to print pArr contents

// (1)
for (int i = 0; i < 3; i++)
cout << "pArr[" << i << "]: " << pArr[i] << endl;
cout << endl;

// (2)
for (int i = 0; i < 3; i++)
cout << "*(pArr + " << i << "): " << *(pArr + i) << endl;
cout << endl;

// (3)
int *pIter = pArr;
for (int i = 0; i < 3; i++) {
cout << "*pIter: " << *pIter << endl;
pIter++;
}

// free memory
delete [] pArr;
return 0;
}
 
 

Comments