I will also try to explain.
Imagine, you have to arrays, maybe:
1 2
|
char a[size];
char b[size];
|
Now you want to copy array b to a:
for( int i = 0; i < size; ++i) a[i] = b[i];
Maybe such a copy would be a good idea and you would need it often, so you could wish to write a function, which does this.
But how could you write such a function? a[i] = b[i] you can't use, because
you don't want to do this only for this a and b.
And therefore we have pointers.
Pointers behave like arrays. But we can do, what we can't do with arrays.
We can assign an address of an array to a pointer:
1 2
|
char * destination = a; // array a
char * source = b; // array b
|
and we could write the same then using the pointers:
for( int i = 0; i < size; ++i) destination[i] = source[i];
Because pointers are not a fix address, but a variable, we can assing other values, increase, decrease and all what we can do with variables.
The example above we could write also in this way:
1 2 3 4 5 6
|
for( int i = 0; i < size ; ++i )
{
*destination = *source;
destination++;
source++;
}
|
*destination could also be written as destination[0].
But consider after we have increased destination, destination[0] then means a[1] and so on
A short form of the example above would be:
for( int i = 0; i < size ; ++i ) *destination++ = *source++;
Because we don't like to write this every time - then we could also have taken the arrays - we could like to make a function:
1 2 3 4
|
void MyMemcopy( char * Destination, char * Source, size_t count)
{
for( size_t i = 0; i < count ; ++i ) *destination++ = *source++;
}
|
And after this we could simply write instead our first copy of array b to a:
MyMemcopy( a , b , size);
You know the function memcpy, which you get, if you #include <memory.h>?
This function we have written now self.
But memcpy performs much faster, because it can use special processor registers for exact this purpose.
Do you understand now the purpose of pointers?