Professional Documents
Culture Documents
Pointers
Pointers
Pointers
Pointers muhammadallee@gmail.com
At a Glance
• Pointers are just like variables that can store address of any memory location.
• Unary ‘&’ is used to take the addresses of the variables. (For arrays, it’s not necessary as name of the array is
itself an address of the memory (starting byte) allocated against it.
• Unary ‘*’ is used to ‘dereference’ the pointer, i.e. to access the memory location pointer is pointing to.
• Size of pointer doesn’t depend on its type, as memory doesn’t have types.
• C++ is type‐safe in case of pointers. (You can only assign the address of those variables that match with the
pointer type or you’ll get a compile time error).
• Actual benefit of using pointers in C++ is to use them for dynamic memory allocation. (In all other cases, use
reference variables instead).
• Just like variables, pointers can be constant too. However for pointers there are two cases, first the pointer’s
own value, secondly the value of the memory location, pointer is pointing at. (Both can be made constants).
Page 1 of 3
Syntax3: (Allocating a N x M array)
<Type>** <Identifier> = new <Type>*[N];
C++ Code:
// Rows of the Array.
int N = 3;
// Columns of the Array.
int M = 4;
if (!iPtr[i])
{
// Error allocating memory, inform user!
// Quit from the program or return error from the function.
}
}
// … Some code
if (iPtr)
{
delete iPtr;
iPtr = NULL;
}
Page 2 of 3
Tips
9 Always initialize the pointer with an address or initialize it with NULL.
9 Usually pointers are used only for allocating/de‐allocating memory; avoid pointing them to variables allocated at
stack.
9 Always test pointers before using them in your code, e.g. consider the following code
if (objPtr)
{
objPtr->AnyFunction();
}
9 Whenever some dynamic memory is allocated using pointers (in classes), always make Copy‐Constructor,
Destructor and overload Assignment Operator, or at least disable them (by declaring them as private).
9 If your class is allocating some dynamic memory and it has at least one virtual function too, mark the destructor
as virtual! (As a general rule, you can declare the destructor as virtual for every class that you make).
9 Always use ‘[ ]’ notation to access the array instead of pointers. For example, use ar[10] instead of *(ar + 10).
9 The function allocating dynamic memory using pointer is also responsible for de‐allocating it. (In case of
constructor, de‐allocate the memory in destructor).
Page 3 of 3