C++ - Understanding Pointers
C++ - Understanding Pointers
Subscribe to admin android apache bash C++ commands database debian fedora filesystem game hardware KDE LPI multimedia
Linuxconfig.org network OpenCV perl program regexp script search security tutorial virtualization vmware VPN
feed
2. What is a Pointer?
#include <iostream>
int main()
{
using namespace std;
// Declare an integer variable and initialize it with 99
A guide to unsigned short int myInt = 99;
programming Linux // Print out value of myInt
kernel modules cout << myInt << endl;
// Use address-of operator & to print out
// a memory address of myInt
cout << &myInt << endl;
return 0;
}
OUTPUT:
Introduction to Linux 99
- A Hands on Guide 0xbff26312
The first line of the output contains an integer value 99 and on the second line, there is a memory address
of myInt printed out. Please note that your output will be different.
#include <iostream>
int main()
{
using namespace std;
return 0;
}
Linux: The Hacking
Solution (v.3.0)
OUTPUT:
The GNU/Linux
Advanced
Administration
The diagram above is a high level visual abstraction of how are variables stored within a computer memory.
Pointer pPointer starts at memory address 0xbff43314 and takes 4 bytes. Pointer pPointer holds as a value
a memory address of a short int twoInt ( 2 bytes ) which is 0xbff4331a. This address is stored as a binary
data within a pointer's memory space allocation. Therefore, dereferencing a pointer with a memory address
0xbff4331a will indirectly access a value of twoInt which is in this case a positive integer 36698.
#include <iostream>
int main()
{
using namespace std;
// Declare an integer variable and initialize it with 99
unsigned short int myInt = 99;
// Declare and initialize a pointer
unsigned short int * pMark = 0;
// Print out a value of myInt
Advanced Bash- cout << myInt << endl;
Scripting Guide // Use address-of operator & to assign a memory address of myInt to a pointer
pMark = &myInt;
return 0;
}
int main()
Popular Linux
Tutorials {
using namespace std;
Bash scripting // Declare an integer variable and initialize it with 99
Tutorial unsigned short int myInt = 99;
// Declare and initialize a pointer
Linux unsigned short int * pMark = 0;
Commands // Print out a value of myInt
cout << myInt << endl;
HowTo
// Use address-of operator & to assign memory address of myInt to a pointer
configure NFS pMark = &myInt;
// Dereference a pMark pointer with dereference operator * and set new value
How to mount
*pMark = 11;
partition with
// show indirectly a value of pMark and directly the value of myInt
ntfs file system
cout << "*pMark:\t" << *pMark << "\nmyInt:\t" << myInt << endl;
and read write
access return 0;
}
Howto mount
USB drive in
Linux OUTPUT:
HowTo mount 99
cdrom in linux *pMark: 11
myInt: 11
Linux lvm -
Logical Volume
Manager Dereferencing a pMark pointer and assignment of new value to 11 will indirectly alter a value of myInt also
to 11. It is important to bring up again that pointer holds only a variable's memory address not its value. To
Linux Software
Raid 1 Setup access a value of the variable to which a pointer is pointing to the pointer must be derefereced by
dereference operator “ * “. Note “ * “ is not a multiplication, by the context of your C++ code your compiler
Linux WD EARS will differentiate if your intention is to use multiplication or dereference operator.
Advanced Hard
Drive Format 7. Pointers and Arrays in C++ Language
In C++ , an array name is a constant pointer to its first element. The relationship between c++ pointers and
C++ :
arrays are closely related and its use is almost interchangeable. Consider the following example:
Understanding
pointers #include <iostream>
How to crack a
int main()
wireless WEP
{
key using AIR
development
using Linux and OUTPUT:
Android SDK
0xbf83d3fc
Introduction to
0xbf83d3fc
Computer Vision
1
with the
OpenCV Library
on Linux As you can see an array name is indeed a pointer to its first element and therefore, is perfectly legal to
access the array elements by a const pointer. Hence, dereferencing an array name will access a value of
Linux DNS
the first element of a given array. The next example will demonstrate how to access other elements of an
server BIND
array by conts pointers.
configuration
return 0;
}
search...
Web
linuxconfig.org OUTPUT:
6
6
Poll 6
The 6th element of an array can be referenced with a pointer expression *(Marks + 5). In addition it is
Do you care
possible to declare another constant pointer and assign it a value of a memory address of the first element
about your
of an array . This pointer will then behave the same way as the originally declared Marks array. The “ + “
privacy when
sign tells the compiler to move 5 objects that are integers from the start of the array. If the object, in an
using a
FACEBOOK? integer, as it is in this our example, ( integer is usually 4 bytes ) this will cause the pointer to point to a
Yes, I do and memory address 20 bytes behind the address reserved by the first array element and thus pointing to 6th.
stopped using The following example demonstrates this idea in detail:
Facebook.
#include <iostream>
No, I do not !
int main()
I have nothing
{
to hide.
OUTPUT:
7.1. Array of pointers
In C++, it is also possible to declare an array of pointers. Such a data structure could be used to create an
array of strings ( string array ). In C++ a string is actually a pointer to its first character, thus a string array
would be essentially an array of pointers to a first character of a string in each array's element.
#include <iostream>
int main()
{
using namespace std;
return 0;
}
OUTPUT:
Debian
Ubuntu
OpenSuse
Fedora
Linux Mint
Mandriva
One solution to this problem is to create global variables. However, this always leads to decreased code
readability, efficiency and bugs, therefore, declaring global variables should be avoided whenever possible.
Declared global variables within a global namespace are holding an allocated memory during the entire
program runtime and very often are needed only for a short time.
Imagine that a programmer will be able to dynamically allocate a memory during a program runtime . This
memory allocation can also be used anywhere within a code and freed any time is no longer needed. This is
where the so called “Free Store” comes in. Free store is a memory available for a programmer to be
dynamically allocated and de-allocated during the program execution.
new operator is to be used when allocating a memory in the free store is needed. Return value of a new
operator is a pointer. Therefore, it should be assigned to only a pointer. Here is an example:
#include <iostream>
int main()
{
using namespace std;
// Delcare a pointer
unsigned short * pPointer;
// allocate a memory with a new operator on the free store
// and assign a memory address to a pointer named pPointer
pPointer = new unsigned short;
// assign an integer value to a pointer
*pPointer = 31;
// Print out the value of pPointer
cout << *pPointer << endl;
return 0;
}
OUTPUT:
31
The free store memory allocated during the program runtime was released only when the actual program
ended. For this short program it is ok, however not de-allocating a free memory back to the system is not a
good programming practice and more importantly your code will normally consist of more than 11 lines.
#include <iostream>
int main()
{
using namespace std;
// Delcare a pointer
unsigned short * pPointer;
// allocate a memory with a new operator on the free store
// and assign a memory address to a pointer named pPointer
pPointer = new unsigned short;
// assign an integer value to a pointer
*pPointer = 31;
// de-allocating memory back to the free store
delete pPointer;
// Print out a value of pPointer
cout << *pPointer << endl;
return 0;
}
OUTPUT:
delete operator frees a memory allocated by a new operator and returns it back to the free store. The
declaration of the pointer is still valid so pPointer can be reassigned. The remove operator just removed
associated memory address with the pointer.
NOTE:It is important to mention that pointers should be always initialized even after delete operator. Not to
do so can create so called a stray pointer which can lead to unpredictable results because a stray pointer
may still point to an old position in the memory and compiler can use that memory address to store other
data. Program can function normally. However, a time bomb to crash the program is set and the time is
running.
#include <iostream>
int main()
{
// define a Heater class pointer object and initialize temperature to 8 by use of constructor
Heater * modelXYZ = new Heater(8);
// Access an accessor function getTemperature() to retrieve temperature via an object modelXVZ
cout << "Temperature of heater modelXYZ is :" << modelXYZ->getTemperature() << endl;
// Free an allocated memory back to a free store
delete modelXYZ;
return 0;
}
OUTPUT:
The largest part of the code above is devoted to a class definition. The interesting segment for us from
pointers perspective is in the main function. Memory from a free store is allocated to a new pointer object
modelXYZ of class Heater. On the next line of this code, an accessor function getTemperature() is called by
referencing a pointer object with an arrow operator. Lastly, a memory set aside from a free store is freed. It
is important to mention that (.) operator which is generally used to access class member functions cannot
be used when an object is declared as a pointer, when a class object is declared as a pointer an arrow ( ->
) operator must be used instead.
#include <iostream>
// FUNCTION PROTOTYPE
// passing to a function by reference using pointers
void addone( int * a, int * b);
int main()
{
// define integers a and b
int a = 1;
int b = 4;
cout << "a = " << a << "\tb = " << b << endl;
// addone() function call
cout << "addone() function call\n";
addone(&a,&b);
// after addone() function call value a=2 and b=5
cout << "a = " << a << "\tb = " << b << endl;
return 0;
}
OUTPUT:
a = 1 b = 4
addone() function call
a = 2 b = 5
Function prototype of addone function includes pointers as accepted variable types. addone() function adds
1 to each variable which a memory address had been passed during the function call, from the main
function. It is imperative to know that using a reference to pointers as passing arguments allow the involved
values to be changed also outside of the addone() function scope. This is a complete opposite to a situation
where a programmer is passing to a function by value. Please see an appendix at the end of this article, for
listed examples on how to pass to a function by value and by reference.
Memory leak takes place when a memory allocated from the free store is no longer needed and is not
released by delete operator. One way this can occur is by reassigning a pointer before a delete operator
had a opportunity to do its job:
#include <iostream>
int main()
{
using namespace std;
// Delcare a pointer
unsigned short * pPointer;
// allocate a memory with a new operator on the free store
// and assign a memory address to a pointer named pPointer
pPointer = new unsigned short;
// assign an integer value to a pointer
*pPointer = 31;
// print out the value of pPointer and its associated memory address
cout << "*pPointer Value: " << *pPointer << "\tMemory Address: " << pPointer << endl;
// reassign a pointer to a new memory address from a free store
pPointer = new unsigned short;
// assign an integer value to a pointer
*pPointer = 15;
// print out a value of pPointer and its corresponding memory address
cout << "*pPointer Value: " << *pPointer << "\tMemory Address: " << pPointer << endl;
// de-allocating memory back to the free store
delete pPointer;
return 0;
}
OUTPUT:
#include <iostream>
// function prototype
void localPointer();
int main()
{
// function call from the main function
localPointer();
return 0;
}
// function header
void localPointer()
{
// function definition
// variable declaration pPointer of type pointer
unsigned short int * pPointer;
// allocate a new memory from the free store and assign its memory address to a pointer pPointer
pPointer = new unsigned short int;
// initialise pPointer
*pPointer = 38;
// print out a value to which pPointer is pointing to
std::cout << "Value of *pPointer : " << *pPointer << std::endl;
// de-allocation statement "delete pPointer;" is missing here
// function end
}
OUTPUT:
Value of *pPointer : 38
When the function localPointer() exits, all variables decalred within a function scope are removed from the
existence. pPointer is also a variable declared locally and therefore, a memory address associated with
assigned memory from the free store will be lost and therefore, impossible de-allocate. The program will run
normally in this simple example. However, every time the function localPointer() is called, a new memory will
be set aside and not freed, which will diminish program's efficiency and cause program crash. More
examples of memory leaks could be found on codersource.net.
11. Conclusion
As it was already mentioned earlier, pointers give a great power to any software engineer who masters
them. This article tried to introduce a pointers in simple way by using examples, so reader can be on a
good way to achieve that goal. Accessing a memory directly by pointers is one of the best features of C++
language and for that reason is often preferable language also for embedded devices programming. Great
caution needs to be taken when working with pointers as great power can swiftly turn into a disaster.
12. Useful links:
Here are some great links to enhance understanding of C++ pointers.
augustcouncil.com: Pointers
13. Appendix
13.1. Write, compile and execute C++ “hello world”
#include <iostream>
int main()
{
using namespace std;
cout << "Hello world\n";
return 0;
}
COMPILE:
EXECUTE:
./hello-world
OUTPUT:
Hello World
#include <iostream>
// FUNCTION PROTOTYPES
int main()
{
// define integers a and b
int a = 1;
int b = 4;
return 0;
}
// add() fuction header
int add( int a, int b)
{
// add() function definition
// this function returns sum of two integers
return a + b;
tmp = a;
a = b;
b = tmp;
}
OUTPUT:
add() function
5
a = 1 b = 4
addone() function
a = 2 b = 5
swap() function
a = 5 b = 2
#include <iostream>
{
temperature = itsTemperature;
}
// definition of destructor
Heater::~Heater()
{
// no action taken
}
// definition of accesor function which returns value of a private Heater class member
temperature
int Heater::getTemperature() const
{
return temperature;
}
int main()
{
// define a Heater class object and initialise temperature to 8 by calling a constructor
Heater modelXYZ(8);
// access accessor function getTemperature() to retrieve temperature via object modelXVZ
cout << "Temperature of heater modelXYZ is :" << modelXYZ.getTemperature() << endl;
return 0;
OUTPUT:
Post as …
Showing 0 comments
Popular
Sort by Popular now
now Subscribe by email Subscribe by RSS
The topics covered in this 500+ page eBook include Linux network, server and data
administration, Linux kernel, security, clustering, configuration, tuning, optimization,
migration and coexistence with non-Linux systems. A must read for any serious Linux
system admin.
back to top