C++ Primer For Java Programmers Pointers<< Text Files | Table of Contents | Dynamic Memory >>
StudentRecord record = new StudentRecord(); a To use the object we must access it indirectly through the sys.out.println( record.idNum + record.gpa ); While Java provides direct access variables for the simple types such as Creating PointersIn C++, pointers can be created for any data type, but once created, they can only store addresses for data of the given type. To declare a pointer in C++, we use the star ('*') notation. In the following code segment, (:source lang=cpp:)int x = 12; int y = 50; int *p = NULL; int *q; we create two C++ allows for the creation of void *vptr;
(:source lang=cpp:) vptr = q;
(:source lang=cpp:) p = (int *) vptr; Pointer AssignmentsAny address can be assigned to a pointer variable so long as that address refers to a variable of the same type as the pointer variable. It is not unusual to assign the address of a varaible to a pointer, we use the address-of operator ( p = &x; results in the address of Dereferencing Pointers.
The value of *p = 8; which results in the following changes Pointer-to-Pointer Assignment.
Two pointers of the same type can be assigned to each other. For example, we can copy the contents of pointer q = p; The result of this assignment is such that both Null Pointers.
You should rmember from Java that a null pointer is one which contains no address and thus points to nothing. In C++, the value p = NULL; the results are illustrated below As in Java, attempting to dereference a null pointer results in a run-time error. Though, in C++ it can be more difficult to locate the actual statement in which the error occurred. Pointer ComparisonsPointers can be used in logical expressions to determine the equality of two pointers. To determine if two pointers point to the same memory location simply compare the two pointer variables (:source lang=cpp:)if( p == q ) printf( "Both p and q point to the same location.\n" ); else printf( "p and q point to different locations.\n" ); } To determine if a pointer is null, compare the pointer variable to the if( p == NULL ) printf( "p is null.\n" ); else printf( "p is not null.\n" ); Function Parameters(:source lang=cpp:)void swap( int *a, int *b ) { int t; t = *a; *a = *b; *b = t; } Double Indirection(:source lang=cpp:)int x = 5; int *p = &x; int *w = &p; printf( "%d\n", **w ); Summary
|