It's probably better to explain with the actual solution.
1 2 3 4 5
|
void printArray(int* array, int sz)
{
for (int i = 0; i != sz; ++i)
std::cout << array[i] << std::endl;
}
|
When you pass an array to a function, you pass the address of the first element. That's why you need to pass the size, because the function only gets a pointer and cannot determine the size of the array from just having a pointer.
There's something we call pointer arithmetic where you can add/subtract values with a pointer. The really important thing to note is the type of the pointer. If you think about it, if a pointer is just a memory address, why does it have a type? It has a type so you can do pointer arithmetic with it.
Consider this:
1 2 3
|
size_t sz = 10;
char* p = new char[sz];
char* q = p + sz;
|
p is of type char, and a char has size 1 byte.
So the expression,
p + sz
has a value of 10 bytes past p.
Consider this:
1 2 3
|
size_t sz = 10;
int* p = new char[sz];
int* q = p + sz;
|
p is of type int, and let's say that an int has size 4 bytes.
So the expression,
p + sz
has a value of 40 bytes past p.
Now, the expression p + 1, is the same as p[1]; and the expression p + n, is the same as p[n]. It's pointer arithmetic that allows us to index into an array. The size of the type of the pointer is used as a multiplier on the index, and that's why pointers have a type.