Example:
|
|
|
TYPE * variableName; |
int * p; // variable p holds an address of an int variable double * q; // variable q holds an address of a double variable |
NOTE:
(int *) p; (double *) q; |
(int *) means:
reference (address) to an int
(double *) means:
reference (address) to a double
|
45 + 78 |
& the reference operator * the de-reference operator |
These operators belongs to low-level programming languages (such as assembler programming)
They are included in C/C++ because C/C++ is a system programming language
|
int i1, i2; short s1, s2; char c1, c2; float f1, f2; double d1, d2; int main(int argc, char *argv[]) { cout << "Address of i1 = " << (unsigned int) &i1 << "\n"; cout << "Address of i2 = " << (unsigned int) &i2 << "\n"; cout << "Address of s1 = " << (unsigned int) &s1 << "\n"; cout << "Address of s2 = " << (unsigned int) &s2 << "\n"; cout << "Address of c1 = " << (unsigned int) &c1 << "\n"; cout << "Address of c2 = " << (unsigned int) &c2 << "\n"; cout << "Address of f1 = " << (unsigned int) &f1 << "\n"; cout << "Address of f2 = " << (unsigned int) &f2 << "\n"; cout << "Address of d1 = " << (unsigned int) &d1 << "\n"; cout << "Address of d2 = " << (unsigned int) &d2 << "\n"; } |
int a; // a can hold an integer value int *p; // p can hold an address of an integer variable &a // is the address of the integer variable a p = &a; // p now contains the address of the // integer variable a // We say that: "p points to a" |
From the above figure, you can see what we say that "p points to a"
|
|
The de-reference operator * is preceeded by typing information:
(type *) Examples: (int *) 3456 is the int value stored at the address (double *) 3456 is the double value stored at the address |
int i1 = 1234, i2; short s1 = -54, s2; char c1, c2; float f1 = 3.14, f2; double d1 =2.718, d2; int main(int argc, char *argv[]) { cout << (unsigned int) &i1 << "\n"; cout << "int value at 136760 = " << * (int*)136760 << "\n"; cout << (unsigned int) &f1 << "\n"; cout << "float value at 136764 = " << * (float*)136764 << "\n"; cout << (unsigned int) &d1 << "\n"; cout << "double value at 136768 = " << * (double*)136768 << "\n"; } |
int * p; // p can hold an address of an integer variable p // is an address (of an integer variable) *p // is the integer variable at that address |
NOTE:
|
int a; int * p; // variable p holds an address of an int variable p = &a; // &a = the address of the integer variable a // p now contains the address of the integer variable a // We say: p "points to" a *p = 1234; // Put the value 1234 into the (integer) variable // pointed to by p // The variable a will be changed !!! |
|
In C++, it is illegal to do this without casting:
double a; int* p; // p references an integer values variable p = &a; // make p point to a double valued variable.... // ILLEGAL (Compile error) !!! |