Neil's C++ Stuff



C++ Arrays Tutorial

Welcome back, glad to see these pages are being used for their intended purpose. This page I have dedicated to the use of arrays. You should be forewarned that:

Understanding Data Types

Before jumping head long into the primordial soup of arrays I want to give you a solid understanding of the basic data types and an analogy that I will pass on to later sections of this tutorial.

Simply speaking a data type is the plans for creating a variable. For example an int is the plans for creating a two-byte number variable, a char is the plans for creating a one-byte character variable. To create a variable of a specific data type we use the following:

[data type] [variable]

Using this context if we wanted to make an integer variable called "x" we would type the following:

int x;

For many of you reading this you no doubt already understand this completely. You're probably impatient and tearing bloody holes in the sides where your clenched fists rest uncomfortably holding the printed copy of this tutorial. So, I'll move on.

What this actually does is create a pin-hole of a few bytes tucked away somewhere in your computer's glutonous memory gut. In the case of our above example it sets aside two little bytes of memory to store whatever value x should ever want to hold. The other memory types you're familiar with and use are char (1 byte), float (4 bytes), and double (8 bytes).

What's the difference between them? Integers (int) can handle whole numbers (no decimals) like -4893 and 7. Characters (char) store single alpha-numeric symbols. Simply speaking (for all of us who prefer the word letters or numbers over the previous) it can store things like '5' and 'c'. When putting these kinds of values into characters you must put the single quotes (apostrophes) around it:

char myvar;

myvar = A;      // WRONG! (missing single quotes)
myvar = 'A';    // RIGHT!

You must use this same techinque when comparing characters to constants:

if (myvar == A)      // WRONG! (missing single quotes)
{
  ...
}
if (myvar == 'A')    // RIGHT!
{
  ...
}

And on to the last two data types: floating-point and double precision floating point. Sounds complicated, eh comrade? They're not really. In laymen's terms (the kind I use) they are used for values that go beyond the decimal point like 1.666 and 777.1. Many people have asked me the difference between the two. Easy, a float is 4 bytes large while a double is 8 bytes. What the heck does this mean? Only that a double can store numbers twice the size that a float could store. What's the point? At this time you needn't worry, use one or the other. Later on when you want to store giant scientific equations and the national debt down to the nano-penny you'll use a double, otherwise it doesn't matter which one you choose. Good? Good!

Prologue to C++ Arrays

*NOTE* Due to the length of social security numbers (9 digits) a 4-byte or long integer (long int) is required. Some of you may have picked up on this. However, if you are using any recent compiler (DJGPP, Visual C++, BC++ Builder) you needn't worry because a normal int actually takes up 4 bytes rather than 2. In other words, anywhere you see something like "an int is two bytes" just remember that now-a-days its usually four.

Before actually discussing the make-up of arrays, let's figure out if they're actually useful. Let's start out by having um ... say 5 different social security numbers. So that means we're going to need 5 integer variables (no letters, no decimals, so I chose integer). Let's say that a picture of a disk represents each of the numbers:

int ssn1; Disk1
int ssn2; Disk2
int ssn3; Disk3
int ssn4; Disk4
int ssn5; Disk5

This is a lot of work! And just think if we wanted to output each of the variables! We'd have to do it individually ... ack, for me being a lazy programmer this is the kind of thing that drives cruel boredom up the base of my spine. But here I'll show you what we'd have to do to print out each and every one of the social security numbers:

cout << "List of SSNs:" << endl;
cout << ssn1 Disk1 << endl
     << ssn2 Disk2 << endl
     << ssn3 Disk3 << endl
     << ssn4 Disk4 << endl
     << ssn5 Disk5 << endl;

Now just think of making a problem to have the user type in 5 social security numbers and then print them out to the screen. Simple right now because there's only 5 variables. Sure sure, but what if suddenly you have to add 5 more? Or 10 more? And then after this what if you have to change how they're outputted to the screen, like instead of one after the other you need commas or something between them. Then you begin to wonder ... is there a better way. OF COURSE! And yup, you guessed it: arrays are the answer (see I had a point for all this rubbish ... and they said I couldn't do it ... they said I was crazy, I'll show them I'll show them! *zzppptt!* okay, I'm better now).

What is an array in C++?

A lot of books like to give complicated explanations and teachers like to throw around the world table like an italian swear word. Table? Heh heh ... well, if you're looking for another definition I got plenty. Here's my first try:

An array is something that you can stick a lot of different things into, but all of them must be the same type.

So an array of humans would be like all these mangled humans stuck into one box. Each of them is different (or can be, who knows - they've done wonders in cloning) but they're all human and that's why they're together in that one box (other reasons escape me ...).

Everyone's seen one of those silly rolodexes right? That's like an array. Each card is a part of the array. They're all stuck in there together because they're all cards (with numbers that you never call unless you really need money). So summing up the defintion (oh I could go on, believe me):

An array is a group of thingies that are together because they are the same type not necessarily the same value.

In this context you can have an array of integer variables, because they are all the same type (integer). However you cannot have an array just based on the fact that all your variables equal 7, unless the type of each variable is the same. So you also cannot have an array that is one part character, two parts float, and four parts integer (poor starbucks *pun pun*). You must have all parts either integer, float, or character.

Now you know what an array is now let me explain why books use the term 'list' to usually describe an array. This is because all arrays (the ones we'll be dealing with at least) are linear. Linear as in top to bottom, one end to the other, straight down. The pieces are arranged right next to each other in order, like:

... ... ... ... ...

Or if you like to thing in up and down terms (I know I do; and no this isn't Tetris):

...
...
...
...
...

Each of the pieces in any array are given a number. This number is basically how you find separate the things. So let us take a box full of humans. Each one is assigned a number that is relative to their position in the array. Dis means that the first person in the box is zero (0), the second is one (1), the third is (2), and on and on. Remember in C++ we always start at zero, not one. So our array would actually look something like this:

[0] [1] [2] [3] [4]

Each of these teeny numbers is called a subscript. You've probably now realized that all the terms are really just made to confuse you. Anyway, therefore the third piece in our array (the very middle one, see there, wave!) is known as subscript 2, the last piece is known as subscript 4, etc. You get the point. So in recapping, because I'm assuming this is all very shocking:

A subscript refers to the order number of a thingie in an array.

There are rules of course, subscripts are always ...

A misconception about arrays is that each piece (subscript) can only store one digit or character. This all depends because as you may have heard on the radio, integers can store several thousand different values and around seven to eight digits. Each part of an array is an individual, not a single digit. Each part of an integer array is an integer variable. Each part of a float array is a float. Going back to our human-filled-box example, each is a whole human not just like an arm or a leg (though that would be interesting :).

Now you know what an array is, and that all the pieces in an array are arranged in a linear order, and that each piece is assigned a subscript. You must learn the last concept (before delving into some code examples). All arrays have a ... NAME!!! Yes, I know its tough but we can get through this, we really can. Every array is called something, just like you call any other variable. Let's call our array "myarray". Pretty innovative, huh?

And since we have named our array, the pieces aren't simply known as just subscript 1 or subscript 3 ... no no, they're now known as subscript (x) of myarray. So, the first piece in our array is now called beloved subscript 0 of myarray. Wow, nifty eh?

Let's add this new concept to our old diagram:

myarray
[0] [1] [2] [3] [4]

Declaring Arrays

Hey, you're here. And by this point you should basically know:

If you do not, then I have not written this as clear as I had hoped. Send me a message or spit in my face (warn me first).

In the succeeding sections I'm going to delve into the process of creating and using arrays in your C++ programs. This section primarily focuses on the declaration of an array.

To declare an array you need to know: what you're going to name it, what type are its pieces going to be (int, char, double, float), and how many piecces its going to have. I'm going to use our ancient social security number examples to portray this stuff.

Remember we had five (5) pieces in our SSN example. So we know our array is going to have subscripts zero (0) through four (4). Previously our variables were ssn1, ssn2, etc. So I'll name our array ssn. We presently have a five (5) part array named ssn which might look something like this in a diagram:

Disk Drive Icon ssn
[0]

Disk1
[1]

Disk2
[2]

Disk3
[3]

Disk4
[4]

Disk5

Ah, how nice and pretty. So that's how our new array looks like when we draw it, but how do we code it in? Simple, we use the following formula:

<data type> <array name>[<size>];

Therefore using that as our guideline, we'd declare ssn like:

int ssn[5];

That's actual C++ code, yes you can type that in and it will work. You can if you wish (many have done this) create an array with more available parts then you are going to use. We could have said:

int ssn[10];

And still only used the first four (4) subscripts but having the possibility of using more (ooh ooh, possibilities). Either way is fine as long as you have created an array with enough parts (five is the bare minimum in our case, any less and our program would burn up somewhere down the line).

The same rules that apply to any other variable apply to an array. If you declare an array outside the main() function then it will be global, and if its inside a function then it is local to that function (can only be used inside that function). It is really easy to pass arrays as parameters (later section) so I would recommend that you make your arrays local to main or wherever.

Accessing the Pieces of a C++ Array

Every piece (or subscript as they have come to be known) of an array works exactly the same as any other variable. If you make a simple integer called "x" then it will work exactly the same as "subscript 0 of ssn". You can add to it, output it, input to it, etc. It works just like any normal variable. The only difference is that it is a part of an array and its name is a number.

Its name is a number!?!? What do I mean by that? By that I mean of course that the pieces are referred to by their subscript. Of course you can't just code into your program a flaunty subscript number and try to treat it like a variable. You have to make sure to state what array the subscript is a part of. Is this complicated sounding or what?

We access the pieces of the array by using the following "blue print":

<array name>[<subscript number>]

Hence if we wished to access the third part of our ssn array ("subscript 2 of ssn") we would do it like so:

ssn[2]

The above is treated EXACTLY like a normal integer variable. Say this with me now, ssn[2] is treated exactly like a normal variable! How what when where why?

Well, you know how to make a single integer variable, and give it a value. Say you make an integer called "x" (famous name, it crops up everywhere in this document). When you want to give it a value of 258 you put something like:

x = 258;

Well, an array is made up of a series of single variables. In our case a list of integers. Each part of an array really is just a single variable and behaves like one. Therefore, we could do the EXACT same thing to ssn[2]! See:

ssn[2] = 258;

The above puts the value 258 into the third part (or subscript 2) of our array ssn. Let's say the white letters show the value of each piece of our array. In doing the above our array would now look like this:

Disk Drive Icon ssn
[0]

0

Disk1
[1]

0

Disk2
[2]

258

Disk3
[3]

0

Disk4
[4]

0

Disk5

This is where my nifty little disk (Disk1Disk2Disk3Disk4Disk5) and drive (Disk Drive Icon) pictures come into play. I figured there's a slight relation to accessing a value from a specific part of an array and accessing information on a disk from a pack of disks (my disk box only holds 5 disks, that's where I got that number, eh eh). To use a value in one section of an array you "put in" a subscript and then you can do whatever you want to that part of the array (output it, change it, etc.). Well, when you want to access a specifc file in your pack of disks, you put in that disk and then you can do whatever you want to that/those file(s) but only as long as you have the disk in there. Without the disk you can't do diddly. Well, without the subscript you can't do diddly either! So I have a little disk drive graphic to represent ssn: Disk Drive Icon, and five little disks to represent each piece of ssn: Disk1Disk2Disk3Disk4Disk5.

If you're still not getting it take a look at this. Say I now want to put a value of 1234 into the fifth part (subscript 4Disk5) of ssn. In code this would look like this:

ssn[4] = 1234;

What we do here is say that we want to use subscript 4 of our array. Then we put the value in. Putting a subscript in the square brackets, is kind of like putting your disk in the drive. You have to do it to access anything in the array. So in my pictionary psuedo code the same thing from above would look like:

1234 » Disk5 » [4] » Disk Drive Icon

And wa la, like I've reiterated a thousand times (poly wanna cracker?) I can now use that one variable, that one piece, that one subscript for anything I want.

Say now I want to output the contents of my array. We could do it like this (you'll see a better way later):

cout << "Contents of array SSN:" << endl;

cout << ssn[0] << endl
        ssn[1] << endl
        ssn[2] << endl
        ssn[3] << endl
        ssn[4] << endl;

Or, what if we wanted to get input into our array:


cout << "Contents of array SSN:" << endl;

cout << "Please input SSN 1: ";
cin >> ssn[0];
cout << "Please input SSN 2: ";
cin >> ssn[1];
cout << "Please input SSN 3: ";
cin >> ssn[2];
cout << "Please input SSN 4: ";
cin >> ssn[3];
cout << "Please input SSN 5: ";
cin >> ssn[4];

Don't get angry on me, I realize that this is just as bad as the first example we saw with the social security numbers. But what I'm attempting to drill into your head is how subscripts work. By this time I hope you can see that you must put in a subscript to use any part of the array. Without a subscript value the array cannot be used by itself.

And when you do put in the subscript value, you're using a single part of the array. And of course you can use this single part like any other variable. The following example shows a subscript being passed to a function that takes a single integer parameter:

/* -example 1--------------------------------------------------------------- */

#include <iostream.h>

void times2(int n);     // prototype a function that takes an integer parameter

void main()
{
  int x;                // create a normal integer variable
  int num[5];           // create an array of 5 integers (subscripts 0,1,2,3,4)

  x = 843;              // give 'x' a value of 843
  num[1] = 843;         // give subscript 1 (second piece) of 'num' value of 843

  times2(x);            // pass the value of 'x' to times2()
  times2(num[1]);       // pass the value of num's subscript 1 to times2()
}

void times2(int n)
{
  cout << "The value you passed to this function is " << n << endl;
  cout << "This number multiplied by 2 is " << (n * 2) << endl;
}

/* ------------------------------------------------------------------------- */

And here is an example showing simple mathematics with the single part of an array:

/* -example 2--------------------------------------------------------------- */

#include <iostream.h>

void main()
{
  int x;
  int num[5];
  int result;

  cout << "Please input a whole number: ";
  cin >> x;

  cout << "Please input another whole number: ";
  cin >> num[3];

  result = x + num[3];

  cout << endl << "The numbers you entered are " << x << " and " << num[3]
       << "." << endl;

  cout << "These numbers added to each other results in " << result << "."
       << endl;
}

/* ------------------------------------------------------------------------- */

Multi-Value Initialization of C++ Arrays

It's really a pain to create an array and then have to set each of its parts individually. Especially when you know what you want each piece to be. Let us imagine for example that we want to make our ssn contain the values: 555001000, 555001001, 555001002, 555001003, and 555001004. We could do this:

int ssn[5];

ssn[0] = 555001000;
ssn[1] = 555001001;
ssn[2] = 555001002;
ssn[3] = 555001003;
ssn[4] = 555001004;

But of course that is really time consuming (which of course I despise). There is a shorter way. Just like you can set every piece of data in a struct at the time of creating it, you can set every part of an array at the time of creating it as well.

Before the semi-colon on the line where you declare your array (int ssn[5];) put and equal sign (=) followed by an open curly brace ({ ). Now at this point you can list the values you want to put in the array. Separate each value by a comma (,) and note that the order you put them in is the order they go into the array. Which means that the first value you type (536843329) will go into subscript zero (0) (ssn[0]), the second value (537853330) into subscript one (1) (ssn[1]), and so on and so forth. When you've listed all the values you want to put in the array, end with a closing curly brace (} ) and a semicolon (;).

This may have sounded like a bunch of gibberish so I'll give you an example:

int ssn[5] = { 555001000, 555001001, 555001002, 555001003, 555001004 };

That's basically how it works. I have no idea how else to explain it so if you don't understand then try it out a couple times on some dummy programs. Also, note that some compilers need an extra subscript space to put their own information for "ending" the array. What does this mean to you? Well, if you get a funny error like "too many intializers" then just add one to the size of the array where you're declaring it. So if you had int ssn[5]; just make it int ssn[6];.

The following example might provide further clarification. It creates an array called num and on initialization puts the numbers 0, 1, 2, 3, and 4 into the pieces of the array. Then it prints the values of all the subscripts in the array. And you can see how the order effects where the values are stored:


/* -example 3--------------------------------------------------------------- */

#include <iostream.h>

void main()
{
  int num[5] = { 0, 1, 2, 3, 4 };

  cout << "The values of array 'num' are as follows:" << endl;

  cout << "subscript 0 = " << num[0] << endl
       << "subscript 1 = " << num[1] << endl
       << "subscript 2 = " << num[2] << endl
       << "subscript 3 = " << num[3] << endl
       << "subscript 4 = " << num[4] << endl;
}

/* ------------------------------------------------------------------------- */

Try it out, you can see that the value 0 is put in subscript zero (0) because that is the first subscript and 0 was also the first value listed. In simpler terms since we listed the value 0 first, it is put into the beginning subscript, which is always 0. I encourage you to try out the above program or make your own.

And the last thing I can give to help you is a statement breakdown:

int ssn[5] = { 555001000, 555001001, 555001002, 555001003, 555001004 };
int this array's parts are integers
ssn Disk Drive Icon array name
[5] size of array
= going to intialize with values
{ begin listing values
555001000 value to put in Disk1 subscript 0
555001001 value to put in Disk1 subscript 1
555001002 value to put in Disk1 subscript 2
555001003 value to put in Disk1 subscript 3
555001004 value to put in Disk5 subscript 4
}; end of statement

Indexing in C++ Arrays

Using a constant number for a subscript value becomes a big pain, especially when your array is several parts long. There is of course a better way of accessing individual subscripts of an array.

Indexing is simple, what it consists of is using a variable instead of a number for accessing a subscript in an array. The variable used in representing the subscript is called the index. The benefit of this is that you can change the index variable and access different pieces of the array.

For instance you already know that to put the value 5 in subscript 2 of ssn you would do something like the following:

ssn[2] = 5;

Now, let me show you the same thing except using an index variable. At this point in the program assume that we have already created an integer variable called i (int i;):

i = 2;
ssn[i] = 5;

Index variables are integers 99.9% of the time. I highly suggest at this point you use nothing else. The value of an index variable follows the same guidelines as a subscript (must be positive, must be a whole number, etc.).

In restating, index variables don't change any part of the array. They simply contain the value for the appropriate subscript. I thought it'd kind of neat to diagram this. Let's say:

int i = 3;

And so, we could diagram num[i] to look something like:

[0]

Disk1
[1]

Disk2
[2]

Disk3
[3]

Disk4
[4]

Disk5
Disk Drive Icon

i = 3

In the diagram our index variable i tells us to use the disk labeled subscript 3. In a program the index variable tells the computer to use the value labeled under subscript 3. Drill drill drill. If you don't have this yet then you have to do ANOTHER exercise.

The advantage really becomes clear when you realize that you can change the index variable's value to effect what part of the array is accessed. For example we could construct a simple while loop:

int i;
int num[5];

i = 0;
while (i < 5)
{
  num[i] = 0;
  i++;
}

In this example we set all five parts of the array num to zero. This of course isn't really useful to use because we could easily intialize the entire array to zero (see previous section for multi-value intializing). However, what if we wanted to print each of the values in the array:

int i;
int num[5] = { 5, 4, 3, 2, 1 };

cout << "Printing contents of array 'num':" << endl;

i = 0;
while (i < 5)
{
  cout << "subscript " << i << " = " << num[i] << endl;
  i++;
}

cout << "Thank you for flying the friendly skies ... " << endl;

Wow, so short. We use a couple lines of code to print out several lines to the screen. The output from above would look like this:

Printing contents of array 'num':
subscript 0 = 5
subscript 1 = 4
subscript 2 = 3
subscript 3 = 2
subscript 4 = 1
Thank you for flying the friendly skies ...

What our program does is continually add to i, but only while it is less than 5. So the first time we go through the loop i is 0. And since we're using i as our index variable we will be accessing subscript 0 which is of course 5. And the loop continues to print each of the subscripts. Then outside of the loop we have a simple cout and then end.

while is the most simple kind of looping. In the case of indexing it hardly is the easiest one to use. You have to initialize the variables before the loop, and increment the counter inside the loop somewhere. Hardly efficient and so I suggest the for loop. for loops are ideal for counting and with indexing this is usually what we want to do anyway! Here's a good example of a for loop in action:

// declare and initialize variables
int i;
int numbers[8] = { 98, 987, 876, 765, 654, 543, 432, 321 };

// output
cout << "numbers[8] = { ";
for (i = 0; i < 7; i++)
{
  cout << numbers[i] << ", ";
}
cout << numbers[7] << " };";

This section has explained the concept of index variables. If you still don't get it then tell me and what you don't understand. Even if you think the question sounds dumb it'll help me make this better. Thanks!

Passing Arrays To Functions

If we were to only use arrays inside main() then their shine would dull slightly. We could always make our arrays global, but that is extremely sloppy coding and functions would lose flexibility. Here is an example of an inflexible program:

/* -example 4--------------------------------------------------------------- */

#include <iostream.h>

int numbers[10], i;

void set_array_to_zeros();
void print_array();

void main()
{
  set_array_to_zeros();
  print_array();
}

void set_array_to_zeros()
{
  for (i = 0; i < 10; i++)
  {
    numbers[i] = 0;
  }
}

void print_array()
{
  for (i = 0; i < 10; i++)
  {
    cout << numbers[i];
    if (i < 9) cout << ", ";
  }
}

/* ------------------------------------------------------------------------- */

This is terribly inextensible. Say perhaps that we wanted to zero-out two different arrays and then print each of those out. Using the previous source as a base, we would have to hard-code (or re-type in) a lot of things. Therefore its almost imperative that you understand how to pass arrays for use in functions.

In any normal function prototype you declare the parameters by coding in their type followed by a name:

void func(int p);

In the previous line we create a function called func which takes a single integer parameter called p. And, when calling this function we'd simply type in the function name (func) followed by a single integer variable or constant inside parenthesis:

int x = 10;

func(10);
func(x);
func(x + 10);

If you understand this concept (and the previous examples) then you're ready for this section otherwise read up more on function parameters. I'll soon be adding a section for this so you'll be able to read that too. Now, moving on we must find a way to pass an entire array to a function.

When you protoype a function to take an array parameter you put in the type of the array (integer, character, etc.) followed by the parameter name, and ending with two square brackets ([]). It looks like this:

type name[]

Following this we could make a function called func that returns nothing (void) and takes a single argument (parameter) that is an integer array called arr:

void func(int arr[]);

The name of the parameter is arr. This parameter is of integer type but is not a single piece. The [] tells us that the parameter is an array. To pass an array to a function you simply use its name, nothing else. So if we were to pass our previous array example ssn to this function func we would do this:

func(ssn);

To use an array parameter in a function we would use it like any normal array, but we'd use the name of that parameter rather than the name of the array that we passed to the function. So say we pass our array ssn to this function func. Inside the function we would not be doing things like ssn[2] = 1011;. Instead we'd be using the name of the parameter, which in this case is arr. So what we would be doing is things like arr[2] = 1011;. See the only difference is that we're using the name of the parameter rather than the name of the array that we passed to the function.

Here's an example of a program which has a function that has an integer array parameter:

/* -example 5--------------------------------------------------------------- */

#include <iostream.h>

void print_array(int arr[], int num_of_parts);

void main()
{
  int numbers[10] = { 328, 53, 2049, 6189, 16, 95, 235, 753, 10963, 1 };
  print_array(numbers, 10);
}

void print_array(int arr[], int num_of_parts)
{
  int i;

  for (i = 0; i < num_of_parts; i++)
  {
    cout << arr[i];
    if (i < (num_of_parts-1) ) cout << ", ";
  }
}

/* ------------------------------------------------------------------------- */

This was a little bit of an "advanced" version of a function because you can use it to print the contents of any integer array. Its first parameter is an integer array called arr and its second is a plain integer called num_of_parts. Because the function does not know how long the array you pass is, we pass a second parameter which tells the function how long the array is. In this example we pass our array called numbers and the value 10. The value 10 is of course how long our array (numbers) is. The function itself uses a for loop and index variable (i) to sift through the array and print each of its subscripts (parts). In our case, i starts at subscript 0 and at the end of each loop iteration, keeps being added to while it is less than 10 (our value of num_of_parts).

To further extend this example we could have added this line below where we declared the numbers array:

int second_array[6] = { 20, 21, 22, 23, 24, 25 };

And then add these two below the line where we call the function print_array():

cout << endl;
print_array (second_array, 6);

After making these changes to our program (try it out), it will print the contents of two arrays: numbers and second_array. And we only had to add a teeny bit of things.

One thing differs about passing arrays to functions compared to passing normal variables. This is that when you normally pass just a regular variable, the function can change the parameter but it does not effect the variable. For instance, take a look at the following:

/* -example 6--------------------------------------------------------------- */

#include <iostream.h>

void func(int param);

void main()
{
  int x = 0;

  func(x);

  cout << "x = " << x << endl;
}

void func(int param)
{
  param = 15;
}

/* ------------------------------------------------------------------------- */

After running this program you will undoubtably get a single line of output:

x = 0

When we changed param inside func it did NOT change x, simply because only x's value was passed. All the function got was the number 0 (the value of x), it did NOT get x itself.

However, when you pass an array to a function parameter any changes made to the parameter will effect the array you passed. Take the following example:

/* -example 7--------------------------------------------------------------- */

#include <iostream.h>

void func(int param[]);

void main()
{
  int x[5] = { 0, 0, 0, 0, 0 };

  func(x);

  cout << "x[0] = " << x[0] << endl;
}

void func(int param[])
{
  param[0] = 15;
}

/* ------------------------------------------------------------------------- */

After running this you will see the line:

x[0] = 15

I won't go into the gorey details of why array parameters behave like this. However, just note that when you pass an array to a function, any changes made to the parameter inside the function effect the actual array. This allows us to easily make functions that calculate relations between two arrays and store them into a result array or to copy one array into another. Here's an example of a program which copies the contents of one array into another:

/* -example 8--------------------------------------------------------------- */

#include <iostream.h>

void copy_array(int source[], int destination[], int num_of_parts);

void main()
{
  int y[5] = { 5, 4, 3, 2, 1 };
  int x[5] = { 0, 0, 0, 0, 0 };

  copy_array(y, x, 5);
}

void copy_array(int source[], int destination[], int num_of_parts)
{
  int i;

  for (i = 0; i < num_of_parts; i++)
  {
    destination[i] = source[i];
  }
}

/* ------------------------------------------------------------------------- */

Contact

Comments or questions? Email me at webmaster@neilstuff.com.