You are on page 1of 9

Pointers and Arrays as Arguments

#include <iostream>

//Illustrates how arrays are passed as parameters and that an array name is

//a pointer that contains the address of the first element in the array

using namespace std;

int main() {

void test1 (int val[], int n);

void test2 (int val[], int n);

void test3 (int *ptr, int n);

int list[5];

for (int j = 0; j < 5; j++) //Stores 5 integers

list[j] = j;
for (int j = 0; j < 5; j++) //Prints 5 integers stored (0, 1, 2, 3 ,4 )

cout << "Initial list[" << j <<"] is " << list[j] << endl;

cout << "************************" << endl;

/*

Initial list[0] is 0

Initial list[1] is 1

Initial list[2] is 2

Initial list[3] is 3

Initial list[4] is 4

************************

*/

test1(list, 5); //list matches up with int val[] in the test1 parameter list

// val and list share the same memory location but val is temporary

// test1 multiplies all elements by 2


for (int j = 0; j < 5; j++)

cout << "list[" << j <<"] is " << list[j] << endl;

cout << "########################" << endl;

/*

list[0] is 0

list[1] is 2

list[2] is 4

list[3] is 6

list[4] is 8

************************

*/
test2(&list[0], 5);

//list contains the address of the first element of list

//can also be written as &list[0]

//values are tripled in test2

for (int j = 0; j < 5; j++)

cout << "list[" << j <<"] is " << list[j] << endl;

/*

list[0] is 0

list[1] is 6

list[2] is 12

list[3] is 18

list[4] is 24
************************

*/

test3(list, 5); //list is a pointer and is copied into

//ptr of test3

for (int j = 0; j < 5; j++)

cout << "list[" << j <<"] is " << list[j] << endl;

/* Multiply list elements by 10 using pointers to access array locations

list[0] is 0

list[1] is 60

list[2] is 120

list[3] is 180

list[4] is 240
*/

system ("pause");

return 0;

void test1(int val[], int max) {

for (int j = 0; j < max; j++)

val[j] *= 2;

void test2(int val[], int max) {


for (int j = 0; j < max; j++)

val[j] *= 3;

void test3(int *ptr, int max) { //pointer arithmetic

for (int j = 0; j < max; j++) {

(*ptr) *= 10;

ptr++;

}
/*

Initial list[0] is 0

Initial list[1] is 1

Initial list[2] is 2

Initial list[3] is 3

Initial list[4] is 4

************************

list[0] is 0

list[1] is 2

list[2] is 4

list[3] is 6

list[4] is 8

########################
list[0] is 0

list[1] is 6

list[2] is 12

list[3] is 18

list[4] is 24

list[0] is 0

list[1] is 60

list[2] is 120

list[3] is 180

list[4] is 240

*/

You might also like