| View previous topic :: View next topic |
| Author |
Message |
manc Grandmaster Cheater
Reputation: 1
Joined: 16 Jun 2006 Posts: 551
|
Posted: Thu Jul 03, 2008 3:41 pm Post subject: [C++] printarray help |
|
|
This code is causing me much vexation. I need a little interpretation help.
| Code: | // arrays as parameters
#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;
}
|
So, it begins at the main function, it defines first and second array. At " | Code: | | printarray (firstarray,3); | " it jumps to void printarray at the top correct? I'm not quite sure what comes next in this situation.
_________________
|
|
| Back to top |
|
 |
Flyte Peanuts!!!!
Reputation: 6
Joined: 19 Apr 2006 Posts: 1887 Location: Canada
|
Posted: Thu Jul 03, 2008 3:45 pm Post subject: |
|
|
It passes a pointer to the array, and the size of the array to the function. The for loop then steps through each item in the array, and then prints it to the console using std::cout.
The code in the printarray() function could be expanded to look like:
| Code: | cout << arg[0] << " ";
cout << arg[1] << " ";
cout << arg[1] << " ";
cout << arg[3] << " ";
...
cout << arg[nLength-1] << " ";
cout << "\n"; |
|
|
| Back to top |
|
 |
manc Grandmaster Cheater
Reputation: 1
Joined: 16 Jun 2006 Posts: 551
|
Posted: Thu Jul 03, 2008 3:54 pm Post subject: |
|
|
Lol, a frequenter of /b/?
And thanks for the help but I think I'm going to come back it when I have more experience, I really don't know what | Quote: | "
It passes a pointer to the array, and the size of the array to the function. The for loop then steps through each item in the array" | means.
_________________
|
|
| Back to top |
|
 |
HomerSexual Grandmaster Cheater Supreme
Reputation: 5
Joined: 03 Feb 2007 Posts: 1657
|
Posted: Thu Jul 03, 2008 9:13 pm Post subject: |
|
|
That means that the function parameter 1 takes a pointer to the array. A pointer to the array is the location of the pointer in memory.
The 2nd parameter takes the length of the array, this lets you know how many digits of the array you want to be read.
Then the loop goes through each memory location and prints out the value of the array.
_________________
|
|
| Back to top |
|
 |
|