understanding arrays as parameters

ok im learning c++ via the online tutorial from this site. this is my first time learning a computer language so please forgive the novice question.
im having a hard time comprehending how arrays are passed as parameters.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using namespace std;
void printarray (int arg[], int length) {
for (int n=0; n<length; n++)
cout << arg[n] << " ";
cout << "\n";
}
int main ()
{
int firstarray[] = {5, 10, 15};
int secondarray[] = {2, 4, 6, 8, 10};
printarray (firstarray,3);
printarray (secondarray,5);
return 0;
}


basically they way i mentally process this is (and PLEASE correct me if my comprehension is wrong) line 3 creates a function [printarray] which will receive an array that's an integer and call it arg and then it will receive an integer variable and call it length. line 4 creates a for then loop, n equals 0; continue loop while n < length and if n < length increment by 1. line 5 tells the computer to display the data being stored in the array at the n address.
skip to line 12 and that's where i start getting a confused.

i know that at line 12 the program calls the function printarray and inserts firstarray and 3 into arg and length, then runs the loop. but i don't get why the loop continues after the first cycle. if n becomes 5, n is less than 3 so why doesn't it quit?

either the author has made an error and my compiler is defying the laws of mathematics because it compiles and executes, returning the exact values as the author stated

3 10 15
2 4 6 8 10

or im an idiot /=
maybe a metaphor on how the for then statement works will help me better understand what the program is executing. i truly am a noob; this is my third day of learning so please don't be too harsh q:

thx
Last edited on
Quick tip. You will notice a format table to the right of the box you can enter you post int.

Select the <> button and place your code within the two tags This will make YOUR code look nice and easy on the eyes.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

#include <iostream>
using namespace std;
void printarray (int arg[], int length) { 
for (int n=0; n<length; n++) 
cout << arg[n] << " "; 
cout << "\n"; 
} 
int main () 
{ 
int firstarray[] = {5, 10, 15}; 
int secondarray[] = {2, 4, 6, 8, 10}; 
printarray (firstarray,3); 
printarray (secondarray,5); 
return 0; 
} 


There are 3 main ways to pass an array. You can pass it the way you are which is a copy, by reference &, and you can pass it as a pointer. A pointer is just a simple data type that stores a memory address. An array is technically a pointer but it is a const pointer. The size of an array must be given at compile time wheres a regular pointer can just be declared and then pointed to an array after the program has compiled.

Passing an array as a pointer is very easy and more flexible imo. The syntax looks like this:

void printarray (int* arg, int length);

Since an array is actually a type of pointer there is no extra syntax required to work with the array in the function printarray.


P.S= you are using a for loop that sets n to 0 each time you call printarray. printarray will print the length of any array that you pass it as long as length is less than or equal to the size of the array. If it isn't you will get what is known as a seg-fault because you will be trying to access memory that isn't allocated.

Seg-faults are good even though they are annoying because they tell us our program is ****** and we should fix it. lol




Last edited on
in line 13 when the function is being called does it replace

n = 0 ; n < length ; n++

with

n = 5 ; 5 < 3 ; n++

that's my understanding of what happens when it passes the parameters. but im pretty sure that's not what's happening because it shouldn't loop if that's the case.
Line 13 does this:
It calls the function printarray, with firstarray as the first argument, and 3 as the second. The 3 is because firstarray has only 3 elements. Now, the for loop looks like so:
 
for(int n = 0, n < 3, n++)


The conditional segment of your for loop is the only thing that will ever change.
oooh thanks so much, i understand now ^-^
i thought it was doing something totally else q:

ps: just to make sure i got this, it would still work if

1
2
printarray (firstarray,2); 
printarray (secondarray,4);
See, the syntax of the for loop is so:
1
2
3
4
for (initialization; condition; increment/decrement/changes in some variable)
{
   //Your code
}


If the condition is true, it executes the code (iteration), and then makes some changes in the variable. If your condition is still true after changing the variable, it executes the code again (re-iteration). The moment the condition becomes untrue, it will not re-iterate and exit the for loop.

So n won't ever reach 5, in the first call of your function where length=3. It'll take value 2 (after 0 and 1), 2<3 is still true, so it will execute, increment n, n will take value 3, 3<3 is False, and hence it will exit.
For length=5, it will take value 0, 1, 2, 3, 4 and execute the code for each. At n=5, it will exit since 5<5 is false...
so i would have to change it to

for (int n=0; n<=length; n++)

in order to use

1
2
printarray (firstarray,2); 
printarray (secondarray,4);
Last edited on
See, the syntax of the for loop is so:
1
2
3
4
for (initialization; condition; increment/decrement/changes in some variable)
{
   //Your code
}


That's not entirely true. You don't have to initialize a variable in the loop itself. The first statement is just the variable to be used in the condition and change.
And kapo, no not really. If you leave it at n < length, it will work fine since array indexes(plural?) start at 0. For example:
1
2
3
4
5
int array[5];
for(int i = 0; i < length, i++)
{
....does something
}


This will work fine if you pass in 5 as the length, because 4 will be the last index of this array. 0 through 4 is 5 elements.
Last edited on
That's not entirely true. You don't have to initialize a variable in the loop itself. The first statement is just the variable to be used in the condition and change.


That is just nitpicking. You failed to acknowledge that you must at least place a semi-colon in place of what should be an initialization variable.

1
2
3
4
5
6
int i;

for (i < 5; i++)  // fail!!!

for (; i < 5; i++) // ok...
Last edited on
I never said you can omit the whole first statement. But I also did not know you could just place a semi colon and call it good.
so even if you initialize the variable before the for statement the parameters will always contain two semicolons?

1
2
3
int i;

for (; i < 5; i++) //is this way bad practice? 
Well in that way, your variable still isn't initialized. It's only declared. Initialization happens when it is assigned a value. I'm not sure exactly how C++ handles it, but in some languages if you don't initialize a variable before you try to use it, you will get some "garbage" that was left behind in that memory location from whatever was there before. You see it a lot with arrays, and other containers.

1
2
3
4
5
6
//These two do the same thing
int i;
for(i = 0; i < 5; i++)

int n = 0;
for(; n < 5; N++)


I personally don't like the second way, but yea you'll always have 2 semi colons.
so even if you initialize the variable before the for statement the parameters will always contain two semicolons?


Yea. You should probably never use a for loop without at least one initialization variable though. The one weird situation where you might not need one is not really enough to convince you otherwise.

Also, if you didn't know, for loops can have several variables and conditions.

1
2
for (int i = 0, j = 0, k = 0; i > j or i ==  k or j < k; i++, j++, k++)
	cout << "This looks crazy doesn't it?\n"; 
Last edited on
1
2
for (int i = 0, j = 0, k = 0; i > j or i ==  k or j < k; i++, j++, k++)
	cout << "This looks crazy doesn't it?\n"; 


"or"???? Shouldn't it be "||"????
"or"???? Shouldn't it be "||"????


http://en.cppreference.com/w/cpp/keywords
Last edited on
Wow... Did not know that!!! Thank you!!!! :)
I didnt know that either. Learned a couple things with this post
Topic archived. No new replies allowed.