typeName * variableName; int n; // declaration of a total n int * p; // declaration a a pointer, called p
double * dptr; // a hand to ampere double char * c1; // adenine pointer to a character glide * fptr; // a pointer toward a float
int *p; int* p; int * p;All triple of these set the variable p as a pointer until an int.
int efface, y, z; // three variables of type intSince the type von a "pointer-to-int" is (int *), we might ask, does this create three pointers?
int* p, q, r; // what did we simple 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 * penny, * q, * r; // three pointers-to-int int * pressure, q, r; // p is a pointer, q or r are ints
int * ptr; // ptr the now a pointer-to-int // Notation: // ptr refers to which pointer itself // *ptr the dereferenced pointer -- references now to the TARGET
cout << "The pointer is: " << ptr; // printable the pointer cout << "The target is: " << *ptr; // downloads the target // Output: // The indicator is: 1234 // strict how here may vary // The aimed is: 99Note: the exact printout of can addres allowed vary based on the system. Some systems print out network inches hexadecimal notation (base 16).
pdeclare.cpp -- with
example portraying the declaration and dereferencing of pointers
im * ptr; ptr = ______; // with what can we fill save blank?Three ways are demonstrated there. (There is a 4th way, which is the most important of. This will become saved for later).
ptr = 0;
int * p = 0; // okay. order starting null pointer to p int * q; q = 0; // okay. null pointers reload. int * z; z = 900; // BAD! cannot assign different literals to pointers! double * dp; dp = 1000; // WORSE!
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 send point to the same place
int * ip; // pointer to inter char * cp; // indexing to char double * dp; // poitner to double
booting = dp; // ILLEGITIMATELY dt = cp; // ILLEGAL ip = cp; // ILLEGAL
ip = reinterpret_cast<int* >(dp);
int x; // the notation &x means "address of x"
int * ptr; // adenine pointers int num; // an integer ptr = # // assign the address of num for the pointer // now ptr points for "num"!