Linux System Administration

Author: Lubos Rendek

Date: 10.09.2009

Update: 04.03.2010 - Section 7.2 was created to clarify relation between Pointers and Arrays in C++

Introduction

This article is intended to all programing enthusiasts on all levels who do wish to understand pointers in C++ language. All code presented here is not a compiler specific and all examples will be written in plain ANSI C++. Debate about pointers can stretch for miles, and you would need to go really far to master it all. If you really want to run that far, this article gives you a clear understanding of fundamental concepts about pointers and prepares you for that journey. However, those who are new to C++ programming make sure that you are able to write and run your own C++ “hello world” program, and also it is recommended that you have a basic understanding of C++ functions and classes. If you need to refresh your knowledge about how to compile and run C++ program, use functions and classes, please read an appendix at the end of this document before you continue reading this article.

What is a Pointer?

Pointer is a variable that stores a memory address. OK, that is simple ! But, what is a memory address then? Every variable is located under unique location within a computer's memory and this unique location has its own unique address, the memory address. Normally, variables hold values such as 5 or “hello” and these values are stored under specific location within computer memory. However, pointer is a different beast, because it holds the memory address as its value and has an ability to “point” ( hence pointer ) to certain value within a memory, by use of its associated memory address.

Retrieving a Variable's Memory Address

OK, enough talking and let's get down to the pointer business. To retrieve a variable's memory address, we need to use address-of operator &.

#include <iostream>
int main()
{
using namespace std;
// Declare an integer variable and initialize it with 99
unsigned short int myInt = 99;
// Print out value of myInt
cout << myInt << endl;
// Use address-of operator & to print out
// a memory address of myInt

cout << &myInt << endl;

return 0;
}

OUTPUT:

99
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.

Assigning a Variable's Memory Address to a Pointer

Before we can assign a memory address to a pointer, we need to declare one. Declaring a pointer in C++ is as simple as to declare any other variable with one single difference. Asterix symbol " * " needs to be add and located after variable type and before a variable name. One rule has to be followed when assigning memory address to a pointer: pointer type has to match with variable type it will point to. One exception is a pointer to void, which can handle different types of variables it will point to. To declare a pointer pMark of type unsigned short int a following syntax is to be used:

#include <iostream>

int main()
{
using namespace std;

// Declare and initialize a pointer.
unsigned short int * pPointer = 0;
// Declare an integer variable and initialize it with 35698
unsigned short int twoInt = 35698;
// Declare an integer variable and initialize it with 77
unsigned short int oneInt = 77;
// Use address-of operator & to assign a memory address of twoInt to a pointer
pPointer = &twoInt;
// Pointer pPointer now holds a memory address of twoInt

// Print out associated memory addresses and its values
cout << "pPointer's memory address:\t\t" << &pPointer << endl;
cout << "Integer's oneInt memory address:\t" << &oneInt << "\tInteger value:\t" << oneInt << endl;
cout << "Integer's twoInt memory address:\t" << &twoInt << "\tInteger value:\t" << twoInt << endl;
cout << "pPointer is pointing to memory address:\t" << pPointer << "\tInteger value:\t" << *pPointer << endl;

return 0;
}

OUTPUT:

pPointer's memory address:              0xbff43314
Integer's oneInt memory address: 0xbff43318 Integer value: 77
Integer's twoInt memory address: 0xbff4331a Integer value: 35698
pPointer is pointing to memory address: 0xbff4331a Integer value: 35698

C++ pointer example diagram

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.

Read more...

Here is a small example of C++ code on how to read a characters from a file as well as to count the number lines of any particular file consist of. The code will check for "\n" the "new line character" and increase the number of lines stored in number_of_lines integer variable. Every iteration will also print single character including "\n" to an output.
First create a file called my-input-file.txt which will contain some text. For example:

welcome to
linuxconfig.org
c++

Then copy c++ code below to a file called read-characters.cpp:

#include <iostream>
#include <fstream>

using namespace std;

int main() {

ifstream fin;
fin.open("my-input-file.txt", ios::in);

char my_character ;
int number_of_lines = 0;

while (!fin.eof() ) {

fin.get(my_character);
cout << my_character;
if (my_character == '\n'){
++number_of_lines;
}
}
cout << "NUMBER OF LINES: " << number_of_lines << endl;

}

and compile it with:

g++ read-characters.cpp -o read-characters

Execute new compiled binary file:

./read-characters

NOTE: your text file must be located in the same directory as your executable read-characters program.

NOTE: while loop and fin.get will add extra new line character so you may start with :

int number_of_lines = -1

OUTPUT:

welcome to
linuxconfig.org
c++

NUMBER OF LINES: 4

Here is a small program to clalculate Fibonacci numbers using c++ language. No tampering with the code needed ( only iprovements ! ) just copy and compile with g++ FibonacciNumber.cpp -o FibonacciNumber and run ./FibonacciNumber

#include <iostream>
#include <cstdlib>

void HowMany(int *numbers);
void CalculateFibonacci(int *numbers);

int main() {

int numbers = 0;

HowMany(&numbers);
CalculateFibonacci(&numbers);

return 0;
}


void HowMany(int *numbers)

{
   // use pointers as parameter, not references
   std::cout << "How many Fibonacci numbers would you like to calculate? ";
   std::cin >> *numbers;
   if ((!std::cin.good()) || ( *numbers <= 1 ||  ( *numbers >= 48 )))

   {
      printf("Invalid number entered ! I calculate only more than 0 or less then 48 Fibonacci numbers !! \n");
      exit(1);
   }

}

void CalculateFibonacci(int *numbers) 
{
	int i = 0;

	unsigned long a = 1;
	unsigned long b = 0;

	unsigned long fibonacci_number = 0;

	while(i < *numbers) {
		b= fibonacci_number;

		fibonacci_number = a + b;
		std::cout << "Fibonacci number: " << i+1 << ". " << fibonacci_number << "\n";

		a = b;
		i++;
	}
	std::cout << std::endl;
}

OUTPUT:

./FibonacciNumber
How many Fibonacci numbers would you like to calculate? 30
Fibonacci number: 1. 1
Fibonacci number: 2. 1
Fibonacci number: 3. 2
Fibonacci number: 4. 3
Fibonacci number: 5. 5
Fibonacci number: 6. 8
Fibonacci number: 7. 13
Fibonacci number: 8. 21
Fibonacci number: 9. 34
Fibonacci number: 10. 55
Fibonacci number: 11. 89
Fibonacci number: 12. 144
Fibonacci number: 13. 233
Fibonacci number: 14. 377
Fibonacci number: 15. 610
Fibonacci number: 16. 987
Fibonacci number: 17. 1597
Fibonacci number: 18. 2584
Fibonacci number: 19. 4181
Fibonacci number: 20. 6765
Fibonacci number: 21. 10946
Fibonacci number: 22. 17711
Fibonacci number: 23. 28657
Fibonacci number: 24. 46368
Fibonacci number: 25. 75025
Fibonacci number: 26. 121393
Fibonacci number: 27. 196418
Fibonacci number: 28. 317811
Fibonacci number: 29. 514229
Fibonacci number: 30. 832040



Free Linux eBooks

Do you have the right skills?

Our IT Skills Watch page reflects an up to date IT skills demand leaning towards the Linux and Unix environment. We have considered a number of skills and operating systems.

See the result...

Linux Online Training

Learn to run Linux servers and prepare for LPI certification with Linux Academy. 104 available video lessons with PDF course notes with your own server!

Go to top