Let's try another, more practical example. What if you wanted to pass an
array of integers to a function? The solution, of course, lies in passing
pointers. As you may or may not know, the name of an array is a pointer to
the first element of an array. So, if you had
If we know how to pass the function the address of the array, the problem is:
How do we declare that we're passing the array to a function? There are actually
two ways to do it, we'll start with the first. Here's how it looks to pass an
array of void eat_at_joes(int guacamole[])
Take a look at how the array of ints is defined. Notice that there is no number
between the brackets -- it's just #include <iostream.h> void eat_at_joes(int guacamole[]) { guacamole[0] = 1; guacamole[1] = 2; guacamole[2] = 3; } void main(void) { int taco[3]; int nacho[2]; eat_at_joes(taco); eat_at_joes(nacho); }
Notice any problems with the example? Take a look at the first call. First,
it defines
Did you notice that the second array, To add insult to injury, the function might run and compile completely flawlessly. Surprised? Well, remember that C++ is based on C, who was of course famous for letting you read or write into a computer's memory without actually knowing if you actually have variables there. Be careful of cases like this, because if you don't catch them, your program will either:
#include <iostream.h> void eat_at_joes(int guacamole[], int size) { if (size > 0) guacamole[0] = 1; if (size > 1) guacamole[1] = 2; if (size > 2) guacamole[2] = 3; } void main(void) { int taco[3]; int nacho[2]; eat_at_joes(taco, 3); eat_at_joes(nacho, 2); }
By adding the second parameter to |