typeName * variableName; int n; // declaration of a variable n int * p; // declaration of a pointer, called p
double * dptr; // a pointer to a double char * c1; // a pointer to a character float * fptr; // a pointer to a float
int *p; int* p; int * p;All three of these declare the variable p as a pointer to an int.
int x, y, z; // three variables of type intSince the type of a "pointer-to-int" is (int *), we might ask, does this create three pointers?
int* p, q, r; // what did we just create?NO! This is not three pointers. Instead, this is one pointer and two integers. If you want to create mulitple pointers on one declaration, you must repeat the * operator each time:
int * p, * q, * r; // three pointers-to-int int * p, q, r; // p is a pointer, q and r are ints
int * ptr; // ptr is now a pointer-to-int // Notation: // ptr refers to the pointer itself // *ptr the dereferenced pointer -- refers now to the TARGET
cout << "The pointer is: " << ptr; // prints the pointer cout << "The target is: " << *ptr; // prints the target // Output: // The pointer is: 1234 // exact printout here may vary // The target is: 99Note: the exact printout of an addres may vary based on the system. Some systems print out addresses in hexadecimal notation (base 16).
pdeclare.cpp -- an
example illustrating the declaration and dereferencing of pointers
int * ptr; ptr = ______; // with what can we fill this blank?Three ways are demonstrated here. (There is a 4th way, which is the most important one. This will be saved for later).
ptr = 0;
int * p = 0; // okay. assignment of null pointer to p int * q; q = 0; // okay. null pointer again. int * z; z = 900; // BAD! cannot assign other literals to pointers! double * dp; dp = 1000; // BAD!
if (ptr != 0) // safe to dereference cout << *ptr;
int * ptr1, * ptr2; // two pointers of type int ptr1 = ptr2; // can assign one to the other // now they both point to the same place
int * ip; // pointer to int char * cp; // pointer to char double * dp; // poitner to double
ip = dp; // ILLEGAL dp = cp; // ILLEGAL ip = cp; // ILLEGAL
ip = reinterpret_cast<int* >(dp);
int x; // the notation &x means "address of x"
int * ptr; // a pointer int num; // an integer ptr = # // assign the address of num into the pointer // now ptr points to "num"!