An array also has a location!
When you declare an array like
char example[32];
in an C program, the variable is (to C) just the location in memory of the first element. It acts just like a fixed pointer.
operator[] is a way of asking for the n'th element after the first one. C/C++ itself has no mechanism to check that the offset you use makes sense. But some compiler do inject code to trap this kind of error.
The difference between the address of an array like example and a normal pointer is that once an array is defined, it's at a fixed point in memory. But a pointer's value can be modified to point at a different bit of memory. So pointers are useful for searching through char arrays.
1 2
|
strcpy(example, "Hello World!");
char* pos = strstr(example, "World");
|
Here, pos will end up as the address of the character 'W' in memory.
I said a "normal" pointer. In C++ you can also declare a pointer as const.
const char* ptr;
is a pointer which can be adjusted to point at a different bit of memory, but you're not allowed to change what it points to.
char const * ptr;
is the same as the last line.
char * const ptr;
is a pointer which points at a fixed bit of memory but can change the value.
char const * const ptr;
is a pointer which points at a fixed location in momory and cannot be moved.
const char * const;
is the same as the last line.
(Don't blame me for the const rules! The rule is that the const applies to the token to the left, unless its's the left-most token itself. Then it applies to the token to its right. Note that the following in invalid as it uses const in the same way twice:
const char const * ptr;
It's the same as writing
const const char* ptr;
)
So, is this helping?