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…

Making An Intro Video

I heard of Adobe After Effects that it is an awesome software for video editing and camera tricks. So, I bought it and tried it out.

I had not done any practice or tutorial before making this intro video below. I am wowed myself! It is too easy to do great and professional stuff…

I hope that you like it.

Of course, it is just a try. I don’t want to make it my true intro video. Maybe, I will just use the same video above and modify it a bit so that, it looks better for my intro video.

Thank you Adobe!

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: Pointers (Part 2)

In the previous post, we learned how to get the memory address of a variable and how to define a variable that holds the memory address i.e pointer.

Suppose that there is a variable of type int called number. We initialize it with value equals to 10. Now, suppose that it has a memory address 091 (Sounds ridiculous but it’s just a supposition). This memory address is present somewhere in our device’s memory.

Some of the memory addresses are shown in the table below, along with the values present in each.

Address 090 091 092 093 094 095
Value Garbage number number number number Garbage

Now, we know that number has a memory address 091. Then, why 092, 093 and 094 are also filled with value, number? Well, just think a little on why not 095? 095 is just a garbage value!

Okay, okay! Let me clear this confusion. number is of type int and the size of int is 4 bytes. Each memory address carries 1 byte. Therefore, to fit a variable of type int, it requires 4 neighboring memory addresses.

So, number is having memory addresses, 091, 092, 093 and 094. But the only memory address that is useful to us, is the first one i.e 091. Every variable only knows its first memory address and its size. When we know the first memory address of a variable, we can easily get the value of that variable.

Now, suppose that we have a pointer of type int called pNumber. We initialize it with the memory address of the number (How to get memory address of a variable? By putting ampersand(&) behind it).

Now, the pNumber is also 091. We dereference it (i.e we put an asterisk(*) behind the pNumber) to get the value 10.

Actually, when we dereference the pointer, we are actually, looking up the memory address which in this case, is 091. Pointer of type int will suggest that whatever is present in this memory address will be the starting byte of the variable which is of type int.

Please read the above statement twice! It is a bit tricky!

To make it easy, here’s the same table:

Address 090 091 092 093 094 095
Value Garbage number —–> pNumber number number number Garbage

After looking up the memory address, pointer takes the value which in this case, is 10.

If you try sizeof() for pointer of any type, it will tell you that the size of pointer is 8 bytes (or may be different depending on your device). This is because a pointer consists memory address and memory address is a hexadecimal value. Hexadecimal values are big values! Therefore, every pointer resembles to type long int which is also 8 bytes in size.

We can manipulate with the pointers as well. We will discuss it in the upcoming posts in detail. For now, just get along with pointers and the concept described above. It should not be hard now! There is still a huge ground to cover regarding pointers…

C++ Programming Series: Pointers (Part 1)

In this post, we are going to discuss pointers. But before proceeding, I just want to say that if you really followed all my posts till now then, Congratulations! You learned the basics of programming in general!

But there are still a lot of basics in C++! C++ is a very old programming language but we still use it because of the fact that C++ is the only language to have a very high performance with object orientation. The term, ‘object orientation’ is a very broad term which we will not discuss in this series.

C++ is powerful because it is a very low level language. And when something is low level, it will be way more flexible but hard to work with. With the help of C++, we can access every bit of our device memory directly. And so, this direct access needs us to be cautious of how it works and what are we really doing with it.

A pointer is the memory address of a variable. I don’t want to say that but learning pointers is a hard thing! Although the definition may looks so simple, to work with pointers isn’t that simple. However, if we understand the way pointer works and all such concepts, it will all be a piece of cake!

Getting the memory address of a variable:

int main()
{
  //As we all know, a basic variable of type 'int'
  int value = 20;
  
  //To get the memory address of any variable,
  //put ampersand(&) at the back of a variable's name.

  //This prints a hexadecimal value which
  //represents the memory address of the variable
  cout << &value << endl;

  return 0;
}

It looks useless but it is very useful! Memory address of a variable is that address inside our device memory where that particular variable is stored. It is a hexadecimal value which is something that is not important to know about. Here is a link explaining what is hexadecimal.

POINTER CONCEPT:

If two variables have same memory addresses, they will act like one variable. Or in other words, a variable can not have two different memory addresses. If we think that a variable have two different memory addresses, they will act like two variables.

Filling a pointer with the memory address of a variable:

//A basic variable of type 'int'
int value = 20;

//Pointer declaration is just like references
//except that it has asterisk(*) instead of ampersand(&)

//A pointer to type 'int'
int* pValue = &value;

//'pValue' is a pointer to 'value'
//or 'pValue' contains the memory location of 'value'

cout << pValue << endl;
cout << &value << endl;
//Both gives us the same memory address

Yup! There is a bit confusion of where to use ampersands, asterisks and other symbols while working with pointers and references. But once we got used to it, it will get easy!

That’s it for now! We will discuss it more later. For now, it is quite much to get used to. No, pointers are not useless! Keep proceeding. Pointers are not a hard subject! I was joking!

C++ Programming Series: File I/O

In this post, we are going to discuss about input and output. No, I am not talking about cout, cin, getline() or any other methods we have discussed till now. I am talking about writing and reading files.

For working with files, we need to include another header called fstream.

There are three classes in it, for file I/O:

  • ofstream – Class for writing files
  • ifstream – Class for reading files
  • fstream – Class for writing as well as reading files

We are going to discuss ofstream and ifstream only. fstream is a bit different to use but who cares! We don’t need that!

The codes for file I/O are present below. It is pretty simple and there is more comment in the code than the code itself, for explaining things!

File Writing:

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
  //The 'ofstream' class for writing a file
  ofstream fileWriter("a_file.txt");

  int number = 21;

  //Writing the stuff
  fileWriter << number;
  fileWriter << " ";
  fileWriter << 13;

  //Closing that file which is opened; it is important!
  fileWriter.close();

  return 0;
}

File Reading:

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
  //The 'ifstream' class for reading a file
  ifstream fileReader;

  //Opening a file called 'a_file.txt' in local directory
  fileReader.open("a_file.txt");

  //For checking whether the file fails to open or not
  if (fileReader.fail())
    cout << "There is no file in the address!" << endl;

  //While the file that is opened, has some context
  //in it at the pointer location
  while (fileReader.good())
  {
    //Variable to store reading from the file
    int number;

    //Reading the number at the pointer location and then,
    //proceeding the pointer forward for further reading
    fileReader >> number;

    //Displaying the number present in the file
    cout << number << endl;
  }

  //Closing that file which is opened; it is important!
  fileReader.close();

  return 0;
}

Reading and writing a file requires us to have the concept of a pointer. The pointer points to some place in the file which then, proceeds forward with every single read/write operation. That pointer is similar to the one which appears at the time of typing.

I hope that you understood how to read and write a file. But there are still some doubts and confusions!

The first one is the formatting of the file that we are reading. White spaces are something that no one wants to read/get from the file. So, ifstream don’t consider these spaces and no matter how much white space there is, it will be considered as one space only.

Of course, we can’t just read data as discrete if that data is arranged without spaces in between. For example, if the file contains two words without any space like this, “nospace”, ifstream reads it as “nospace” and so, giving a space between them rectifies the issue.

The second one is the data type for reading and writing a file. We can use all primitive types. We can use strings as well if we include the string header.

The third one is formatting a file being written. We can have formatting by just writing in character literals like \t or \n to have a tab or a new line respectively.

This is how we simply read and write files. Now, your task is to modify the registration program that we made with functions previously, to write a file with the data inputted by the user.

Soon we will see, how much fun is programming! It is fun for me as I am developing a game in C++ called SamuraiDuel.

Featured

Developing a Game: SamuraiDuel

Now-a-days, I am developing a game called SamuraiDuel. It is going to be a 2D game and being built on OpenGL, SDL2, Box2D and CEGUI all in the language, C++.

SamuraiDuel Title
SamuraiDuel Title

Before starting to develop the game, I first developed the base of a very low level Game Engine which I should call a GL Engine, GL SDK or something like that, in order to work with OpenGL with ease. Of course, I called it BAC GL Engine 2 (I tried to make one before but it has some big flaws and so, I put ‘2’ this time after the name).

I am not satisfied with that name. If you had one in your mind, please do comment below.

SamuraiDuel is going to be a side scroller fast paced pixelated game. Of course, it will take time to get completed and once it is completed, this is the place where I will confirm this.

There is the screenshot of the game! I hope that you like that…

SamuraiDuelDevelopment4

All pixel arts are made by me and I think it looks fair.

That’s all that I have to say! If you want some features in it or just has something to tell, comment below and tell that to me! It will be really appreciable.

UPDATE: The project is closed and is no more under development due to lack of funding and maybe, motivation. Sorry guys! But who knows… I might complete it someday!