C++ Programming Series: Pointers (Part 4, Last)

Too busy! Too busy! Don’t expect regular and weekly posts from me. I am studying medicine.

In the previous post, we discussed that pointers are actually arrays! This post is to discuss more about pointers, arrays and the arithmetic that can be done with them.

We can do addition and subtraction with pointers. Multiplication and division is not possible! Here is the code giving an example of pointer arithmetic (try to understand it deeply):

int array[] = {20, 30, 40, 50, 60};
int* pArray = array;

pArray++;
cout << *pArray << endl; //Prints 30, same as array[1]

pArray++;
cout << *pArray << endl; //Prints 40, same as array[2]

cout << pArray[2] << endl; //Prints 60, same as array[4]
//pArray[4] will give error or garbage value!

pArray -= 2;
cout << *pArray << endl; //Prints 20, same as array[0]

cout << pArray[4] << endl; //Prints 60. same as array[4]

When we increment a pointer of type int, the address is actually shifted by the number of bytes that an integer consists of. Similarly, when we increment a pointer of type string, the address is shifted 4 bytes forward. The opposite happens when we decrements a pointer.

Consider the code below:

string words[] = { "First", "Second", "Third", "Fourth", "Fifth" };

string* pWords = words;

Now, pWords is pointing towards the memory address of words[0] or “First”. If we add one into it:

pWords++; //or pWords += 1;

…then it will be shifted 4 bytes forwards to reach the next string of the array, words. Or in other words, pWords is now, equivalent to &words[1]. Now, if we subtract one from it, it will get to the same address as before.

C++ is a very flexible language. We can add the numbers into the pointer temporarily like pWords + 3. Now, if pWords is equivalent to &words[0], then pWords + 3 would give us the address equal to &words[3]. If we dereference this memory address, we will get the proper string value, “Fourth” like this:

string words[] = { "First", "Second", "Third", "Fourth", "Fifth" };
string* pWords = words;

//Adding temporarily for getting the memory address of the
//fourth element of array and dereferencing that memory
//address to get the value from there
cout << *(pWords + 3) << endl; //Prints "Fourth"

Isn’t that similar to that?

cout << pWords[3] << endl; //Prints "Fourth"

Yes, they are completely the same! What is happening with pWords[3] is the same as what is happening with *(pWords + 3).

That’s it! Your exercise is to find out what is the output of the code below (without checking it out in the compiler):

int array[] = { 1,2,3,4,5,6,7,8,9,10 };
int* pArray = array;

pArray += 5;
cout << pArray[3] << endl; //Output 1
pArray -= 3;
cout << pArray[4] << endl; //Output 2
pArray--;
cout << *pArray << endl; //Output 3
pArray + 2;
cout << *pArray << endl; //Output 4
pArray += 1;
cout << *(pArray + 1) << endl; //Output 5

That is all pointers for you. Congratulations! You learned the pointers! Time to step ahead…

C++ Programming Series: Pointers (Part 3)

Pointers and Arrays are same things!

This statement might confuse you. How is this possible that pointers and arrays are same? They never looks to be same!

This post will clear this point to you. Lets get started with the code below.

int array[5] = { 3, 4, 7, 8, 12 };

//Look! We have not put square brackets
//with a number after the name of array
cout << array << endl;

What will it print? Will it print the first member of the array? No, it will print the memory address of the first member of the array.

Now, you see that there is no ampersand(&) needed for getting the memory address of the array. Don’t you think that it is something that is similar to pointers? Yeah, but this is not all!

int array[5] = { 3, 4, 7, 8, 12 };

//'pArray' is now pointed to the first member of the 'array'
int* pArray = array;

//Now, we can use 'pArray' similar to that of 'array'
cout << pArray[2] << endl; //Prints 7; same as 'array[2]'

The above code explains that pointers are actually arrays! We can have square brackets with pointers and just use it exactly as an array.

Another point to tell you that when we use a pair of empty square brackets([]) after a pointer or an array, it will still give us the memory address of the array. But when we mention the number in it, pointer or array will give us that particular value under the index.

Pointers and arrays are same things but there is only one difference between them.

An array knows that how many elements it has. If we use sizeof() method for an array, we will get right number of bytes that it occupy.

int array[5] = { 3, 4, 7, 8, 12 };

//We can use empty square brackets as well
cout << sizeof(array[]) << endl; //Prints (sizeof(int) * 5)

Note: Size of integer may be different for your device. Mine is 4 so, it will result in 20. It may result 10 as well.

A pointer never knows that how many elements it has. It may or may not be an array as well. If we use sizeof() with pointer. we will not get the right number of bytes that it occupy. A pointer do know about the size of type that it is of.

int array[5] = { 3, 4, 7, 8, 12 };
int* pArray = array;

cout << sizeof(pArray[]) << endl; //Prints 2, 4 or 8 (not true in any case)

What if we want to pass array to a function? We have never discussed that topic before. Now, there is something that I have to tell! We can’t pass array to a function! So, there you go. The topic ends.

Of course, there is a solution to this problem. We can’t pass arrays but we can pass pointers to a function. Unfortunately, we can’t get the size of array that is passed as a pointer. Therefore, we have to pass the total number of elements to the function as well.

void printIntegerArray(int* pArr, int totalElements)
{
  for(int i = 0; i < totalElements; i++)
  {
    cout << pArr[i] << endl;
  }
}

int main()
{
  int array[5] = { 3, 4, 7, 8, 12 };

  //We don't need to make any pointer
  //Pointer is just a memory address
  //So, we can pass array directly
  printIntegerArray(array, 5);

  return 0;
}

Just keep in mind, the concept that pointers are arrays but they don’t keep track of their number of elements. There are few things that are not clear. We still don’t know what happens behind that pair of square brackets with a number in it. We will discuss pointer arithmetic in the next post along with the working behind square brackets.

Exercise: Make a function that takes an integer array and prints only even numbers.

C++ Programming Series: Multidimensional Arrays

In the last two previous posts, we discussed a very useful thing called as ‘Arrays’. This topic is not yet completed and this post is going to end it! Multidimensional arrays!

Previously, we discussed 1D (or single dimensional) arrays. They are pretty simple.

int arr[10];
arr[0] = 2;
arr[3] = 10;
arr[7] = 40;
//arr[10] is not possible, will give error!
cout << arr[0] + arr[3] + arr[7] << endl; //Outputs 52

But now, time for 2D and 3D arrays. We won’t go in details with 3D because they are like 2D, understanding 2D array will give us the understanding of 3D arrays as well. Also, 3D arrays are rarely used.

int arr1d[3] = {1, 2, 3};

int arr2d[3][3] =
{
  {1, 2, 3},
  {4, 5, 6},
  {7, 8, 9}
};

int arr3d[3][3][3] =
{
  {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
  },
  {
    {10, 11, 12},
    {13, 14, 15},
    {16, 17, 18}
  },
  {
    {19, 20, 21},
    {22, 23, 24},
    {25, 26, 27},
  }
};

cout << "1D Array:-\n";
for (int x = 0; x < 3; x++)
  cout << arr1d[x] << " ";
cout << endl;

cout << "2D Array:-\n";
for (int y = 0; y < 3; y++)
{
  for (int x = 0; x < 3; x++)
  {
    cout << arr2d[y][x] << " ";
  }

  cout << endl;
}

cout << "3D Array:-\n";
for (int z = 0; z < 3; z++)
{
  for (int y = 0; y < 3; y++)
  {
    for (int x = 0; x < 3; x++)
    {
      cout << arr3d[z][y][x] << " ";
    }

    cout << endl;
  }

  cout << endl;
}

Dimensions are increased by putting another pair of square brackets. Number of elements in a multidimensional array will be the product of the values in each pair of square brackets that are typed in during the initialization of that array. For example, in the above cases, arr2d has 9 elements and arr3d has 27 elements. Below is how you can access elements of arr2d, individually.

//cout << arr2d[0][3] << endl; Gives error or garbage value
cout << arr2d[0][2] << endl; //Outputs 3
//cout << arr2d[3][0] << endl; Gives error or garbage value
cout << arr2d[2][0] << endl; //Outputs 7
cout << arr2d[1][1] << endl; //Outputs 5 (middle element)
cout << arr2d[2][2] << endl; //Outputs 9 (last element)
cout << arr2d[1][2] << endl; //Outputs 6
cout << arr2d[2][1] << endl; //Outputs 8

Remember, array index number starts from 0 and not 1. The concept behind multidimensional arrays, is the fact that each 2D array consists of 1D arrays, which contain elements and so, each 3D array consists of 2D arrays, which further, consists of 1D arrays, which contain elements. I know that sounds complicated!

//Number of 1D arrays present in the 2D array
//is the number typed in the 1st pair of square brackets
int arr2d_2[1][3] =
{
	{ 1, 2, 3 } // -> Only one 1D array in a 2D array
};

The tricky question is, how to access all elements of a multidimensional arrays with sizeof()? It is pretty simple but tricky! Simply, to get the total number of sub-arrays or max index value of first pair of square brackets, divide the memory size of whole multidimensional array with the memory size of sub-array. And then, to get the total number of elements in each sub-array, divide the memory size of a sub-array with the memory size of an element.

string machines[2][4] =
{
  { "Calculator", "Computer", "Printer", "Scanner" },
  { "Microwave Oven", "Blender", "Refrigerator", "Juicer" }
};

//Memory size of whole array: sizeof(machines)
//Memory size of sub-array: sizeof(machines[0])
//Memory size of element: sizeof(machines[0][0])

//Total number of elements = sizeof(machines) / sizeof(machines[0][0])

//sizeof(machines) / sizeof(machines[0]) = 2
for (int y = 0; y < sizeof(machines) / sizeof(machines[0]); y++)
{
  //sizeof(machines[0]) / sizeof(machines[0][0]) = 4
  for (int x = 0; x < sizeof(machines[0]) / sizeof(machines[0][0]); x++)
  {
    cout << machines[y][x];

    //To avoid putting comma after the last element of each sub-array
    if (x != (sizeof(machines[0]) / sizeof(machines[0][0])) - 1)
      cout << ", ";
  }
  cout << endl;
}

I am pretty sure that it is complex. But if you code and practice on your own, you will found it to be easy! The good thing about 2D arrays is the fact that you can manage data in the form of tables! Try to make a table of numbers ranging from 0 to 100 where each sub-array or 1D array in the 2D array, will have 10 elements. It will be better if you use sizeof() for outputting the table.

That’s all! I hope you got it all right!

C++ Programming Series: Char, Char Arrays and Strings

As we know that char is one of the primitive types whereas string is not a primitive type. Let us reveal some more facts about the two.

char is basically, a number like int. But that for each particular number, a specific letter or symbol is selected in accordance with the ASCII table. You can convert a char to an int temporarily to have the output, a number which represents that character.

In the main method:

char letter = 'b'; //Remember to use single quotes for 'char'

cout << (int)letter << endl; //Converting 'char' to 'int' and then, outputting.

We can convert a type into the other type. Type conversions have many methods and is not an easy topic. We will discuss it in details later on.

In other words, we can increment char to have the next letter. If we do letter++; before outputting it in its original form, the character will be ‘c’.

Following is an array of characters:

char word = { 'H', 'e', 'l', 'l', 'o' };

//Size of a single 'char' is 1 byte. So, 'sizeof(word)' gives 5.
for(int i = 0; i < sizeof(word); i++)
  cout << word[i] << endl;

The char array is a special case. There can be a very easy implementation to char arrays in order to use them just like the non-primitive type, string.

char word = 'Hello'; //Just like 'string' accept for single quotes

cout << word << endl; //No looping, pretty straight! Prints "Hello".

String is a group of char and can be considered as an array of them. It has many features and so, is better than a regular array of char. We will go deep into strings later on but for now, here’s the array of string:

string word = "Hello";

cout << word << endl;

string sentence[] = { "Hello,", "this", "is", "a", "sentence." };

for(int i = 0; i < sizeof(sentence)/sizeof(string); i++)
  cout << sentence[i] << " ";

The basic difference between a string and a char array is that string contains a special character at the end of the array of characters, called as the null terminating character which tells the compiler to end the string and proceed. In the case of the string called word, it is present after the ‘o’ of ‘Hello’.

This is pretty much for now and it might help you in handling with characters and strings in C++. There are many confusions between the two and is usually, mismatched in both, theoretical and practical ways. Try to do calculations with char, char arrays and strings, and figure out better ways yourself!

C++ Programming Series: Arrays

Previous two posts are (or just looks like) useless and really, are not interesting. But in this post, you are going to get the reward! Yes, a reward! You are going to learn my favourite thing, favourite in the way that it makes life with programming very easy! We call it: Arrays.

Before proceeding, remember that this post is a very long post because it is very significant.

What is an array? Array is a list of something; group of variables of a specific type. They are group together in a linear way just like ‘3 after and 2 before the 1’.

#include <iostream>
using namespace std;
int main()
{
  //This is an array of integers which holds 5 elements(variable of type 'int')
  int array[5] = { 5, 10, 15, 20, 25 };

  //Printing all elements of the array using index.
  //Possible indexes are from 0 to 4, not 5 as it don't starts from 1.
  //Anything other than that, would give you error or just garbage values!
  for(int i = 0; i < 5; i++)
  {
    cout << array[i] << endl;
  }
}

It looks very simple and I hope that you may have got it here! Array of variables can be for any type! It is not necessary to put 5 before 10 and so on, you can put any number for any index. Here is the format of an array declaration:

-type- -name- [-number_of_elements-]; 

It’s too simple to make one. To initialize every element of an array, there is another method. Just like we output the element of an array via the index, we can alter that number as well!

int array[5]; //Only declaration

for(int i = 1; i <= 5; i++)
  array[i-1] = i*5; //i-1 as index to get a proper range of 0-4 instead of 1-5
//array is now = 5, 10, 15, 20, 25

array[0] = 10; //previous value = 5
array[1] *= 100; //previous value = 10
array[2] -= 5; //previous value = 15
array[3] = 0; //previous value = 20
array[4] %= 5; //previous value = 25

It might be possible that the for-statement and %= may look unclear to you. If that is the case, please check out my previous posts on C++ Programming Series to remember them.

Arrays are just a list of elements with the number of elements or range of indexes unalterable or constant. We can’t change the total number of elements in an array! But there are arrays which can have alterable number of elements; this term is associated with STL or C++ Standard Template Library which we will talk about later.

In the first block of this post, it is not necessary to type in the total number of variables inside the square brackets as the compiler can check that by the number of elements in between the curly brackets. It is not possible to initialize only one or two variables in between the curly brackets, we must initialize all variables in such a case.

Now, we are going to discuss a small case of arrays to pinpoint two things: its importance and the sizeof() operator’s importance (yeah, that useless sizeof()!)

Suppose that we are going to make a game with many enemies. Lets say that they are just 100 in count and we need to have a variable that holds the health for each!

Lets us try to do it without arrays. In the main(or int main()) method:

int enemy1_HP = 10;
int enemy2_HP = 10;
int enemy3_HP = 10;
//and so on to...
int enemy99_HP = 10;
int enemy100_HP = 10;

//ISN'T THAT SOMETHING LENGTHY WHICH DOES
//NOTHING BUT KEEP TRACK OF ALL ENEMIES HP?

OK? Is that OK? If your answer is ‘No’, then you really don’t like to work hard. But if it is ‘Yes’, then I should have told you that you also need a variable for the position, speed, attack, bullets, coins… and more. Just with the mentioned ones, there will be about 500 lines of code! That is one of the reasons why we should not measure a programmer’s capability by the number of lines in his/her program.

Apart from the problem of having a lot of lines being wasted on variable declaration, there is an even bigger problem! Just tell me, how are you supposed to combine your 100 enemies’ variables with the looping? I mean that there is nothing like index in a large list of singleton variables. It will just get more and more complex!

In short, it will take enough time to complete the game without arrays that we will begin to hate programming. Of course, it is NOT OK at all!

Here is with arrays:

//Replacing 100 lines with just 3!
int enemyHP[100];
for(int i = 0; i < 100; i++)
  enemyHP[i] = 10;

//I am in love with arrays!

The index can serve as an ID number for the enemy and you can always get and set the health, position, speed, attack, bullets, coins, etc, of the appropriate enemy just by having the ID or index of that enemy.

Now, at the end of the program, for some reason, you want all enemies’ health(or HP) to be equal to zero. Lets say that the program consists of more than 10000 lines of code and 100 files. At the specific line of a specific file, there is the declaration of the enemyHP array. You just forgot the total number of elements in that array. Finding the declaration in the files might take some time. Your IDE have the feature to find the declaration but you don’t know how to access that feature. So, what? We can always use sizeof() to find out the amount of memory allocated by the variable or even array.

In this case, it will give the value 400 for enemyHP array. For each integer, it will have 4 bytes and so, for 100, 400 bytes. So, we need to divide sizeof(enemyHP) by sizeof(int) to get the total amount of elements for that array:

for(int i = 0; i < sizeof(enemyHP)/sizeof(int), i++)
  enemyHP[i] = 0;

And there you go! It is ended and with every post, our database are getting expanded. I can’t just let you go with nothing so, here are some exercises. Strictly speaking, if you are learning programming for the first time with this series of post, just stick with the first 3 exercises. Don’t bother to see the exercises beyond the third one because they might confuse you. The first 3 exercises exercises assumes that you must have some knowledge about console printing, arrays, user input, conditional statements. Just try these 3 exercises. If you get failed to get proper results, try to fix the problems in your code. But after that, if you still get failed, just check out the solution given with the exercise.

To learn how to program stuff is just like to learn how to paint stuff. It just gets better with you, trying to do it, face it and then, experiment with it, again and again, and not just by reading and watching tutorials.