How to pass a pointer to an array to a function C++ program example


Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows 2003 Server Standard Edition

Header file: Standard

Additional project setting: Set project to be compiled as C++

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)

Other info: none

To do: Displaying arrays' elements demonstrating passing a pointer to an array to a function for processing in C++ programming

To show: How to pass a pointer array to a function in C++ programming




// a program that passes a pointer to an array to a function

#include <iostream>

using namespace std;


// function prototype for viewArray

void viewArray(int *[ ]);


void main(void)


// declare and initialize the array variable

int i,*arrayPtr[7], var[7]={3,4,4,2,1,3,1};


// traverse the array

for(i=0; i<7; i++)

// arrayPtr[i] is assigned with the address of var[i]

arrayPtr[i] = &var[i];

// a call to function viewArray, pass along the pointer to the 1st array element





// arrayPtr is now passed to parameter q, q[i] now points to var[i]

void viewArray(int *q[ ])


int j;


// displays the element var[i] pointed to by q[j] followed by a space. No value is returned and control reverts to main()

for(j = 0; j < 7; j++)

cout<<*q[j]<<" ";



Output example:


3 4 4 2 1 3 1

Press any key to continue . . .



C and C++ Programming Resources | C & C++ Code Example Index