SatView: Pointer Perfect, Part 1 - The pointer-to-member operator
(Page 3 of 5 )
When you are using classes or structs (do you know what the difference is between them in C++?), you can use the pointer-to-member operator (->) to retrieve/set their values or call their functions. Consider this class:
class MyClass {
public:
MyClass() : myVar(10) {}
int myVar;
};
Assume you are using it the following way:
MyClass myThing;
MyClass *pPtr = &myThing;
then you can access MyClass::myVar with the pointer-to-member operator:
pPtr->myVar = 20;
or use the reference operator if you like:
(*pPtr).myVar = 20;
... the outcome will be the same.
Pointer arithmetic
It is possible to conduct arithmetical operations on pointers, although only the addition and subtraction operators can be used. This is very useful when you need to traverse a block of contiguous memory, filled sequentially with instances of a single type. Depending on the size of the type, you will get different results (you can determine the size of a type with the sizeof(<type>) operator).
Lets take a look at a simple string example:
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]) {
char *str1 = “string one”;
wchar_t *str2 = L“string two”;
char *pPtr1 = str1;
(void)printf(“address of pPtr1: 0x%p\n”, pPtr1);
(void)printf(“address of pPtr1+1: 0x%p\n”, pPtr1+1);
wchar_t *pPtr2 = str2;
(void)printf(“address of pPtr2: 0x%p\n”, pPtr2);
(void)printf(“address of pPtr2: 0x%p\n”, pPtr2+1);
return 0;
}
Your output will be similar to:
address of pPtr1: 0x00424038
address of pPtr1+1: 0x00424039
address of pPtr2: 0x004246E0
address of pPtr2+1: 0x004246E2
Notice how pPtr1+1 increased with 1 and how pPtr2+1 increased with 2! This is because sizeof(wchar_t) is 2. If we had been working with pointers to int, you could have seen an increase of 4 (if you want to be sure what the size of int - or for that matter of any type - is, use the sizeof operator!).
Next: Pointer casting >>
More Code Examples Articles
More By J. Nakamura