how does the entire array eventually get passed to the function to be used? |
Well technically you're not passing the entire array. What actually happens is a bit of pointer math.
First, let's step back and look at what an array is. An array is simply a group of variables that are stored one after the other.
|
int foo[5]; // has 5 'int's, stored sequentially
|
Accessing the individual variables in that array is known as "indexing". You provide an index which indicates which variable from the group you want. C/C++ provides a very simple way to do this using the [] operator:
|
cout << foo[1]; // prints the second 'int' in the array (index 1)
|
Now what is really going on with indexing is, the index is getting added to the start of the pointer, which gives you a pointer to the individual variable you want. Consider the following code:
1 2 3
|
int* ptr = foo; // point to start of the array
ptr += 2; // add 2 to the pointer (this moves the pointer forward 2 'int's)
if(ptr == &foo[2])
|
The if statement here will come back as true, because by adding 2, 'ptr' now points to index 2 of the array. Realizing this... you realize that the [] operator is just a shortcut for pointer math:
So "passing an array" to a function can be accomplished by passing a pointer to the first element, because elements after the first can be "found" with pointer math.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
void func(int* ptr)
{
ptr[2] = 10;
}
int main()
{
int foo[5] = {1,2,3,4,5};
func( foo );
int i;
for(i = 0; i < 5; ++i)
cout << foo[i] << ", ";
return 0;
}
|
This code would output "1, 2, 10, 4, 5, " -- because when we passed the foo pointer to our func, it changed foo[2].
char arrays work the same way. But with chars instead of ints. Functions can read the entire string as long as they know where the string starts.