Download presentation
Presentation is loading. Please wait.
1
Pointers Lecture 1 Thu, Jan 15, 2004
2
Topics Pointers Declaring Pointers Null Pointers The Address Operator
Dereferencing Pointers Pointers to Void Assignment of Pointers 2/22/2019 Pointers
3
Pointers A pointer is an object that refers to another object.
A pointer holds the address of the object that it refers to. All pointers occupy 4 bytes of memory. 2/22/2019 Pointers
4
Declaring Pointers Write the type of object that the pointer points to, followed by *, followed by the pointer name. int* pi; float* pf; 2/22/2019 Pointers
5
Null Pointers A null pointer is a pointer that has the value zero.
A null pointer does not point to any object. The constant NULL has the value 0. It is a good practice to initialize a pointer to NULL. int* pi = NULL; 2/22/2019 Pointers
6
The Address Operator The unary prefix operator & returns the address of an object. The address may be assigned to a pointer. Example: AddressOperator.cpp int i; int* pi = &i; // &i is address of i 2/22/2019 Pointers
7
Dereferencing Pointers
When a pointer is dereferenced, it returns the object that it points to. The unary pre-fix operator * is used to dereference a pointer. Never dereference a null pointer. Example: DereferencePointers.cpp int i = 10; int* pi = &i; // pi points to i cout << *pi << endl; // Print i 2/22/2019 Pointers
8
Pointers to void A pointer to void (void* object) is a pointer that does not point to any particular kind of object. (void “objects” do not exist.) void is treated as a “neutral” type for situations where the type does not matter. A void pointer may hold the address of any object. A void pointer may not be dereferenced. 2/22/2019 Pointers
9
Assignment of Pointers
The pointer assignment p1 = p2 is legal if and only if p1 and p2 point to the same type of object, or p1 is a pointer to void. Otherwise, cast p2 to be compatible with p1. Assigning pointers to different types can cause serious problems. 2/22/2019 Pointers
10
Example: Pointer Assignment
Example: PtrCompatibility.cpp void* pv; int* pi; float* pf; pv = pi; pi = (int*)pf; pf = (float*)pv; 2/22/2019 Pointers
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.