Saturday 19 December 2009

C pointers - Part - I

C pointers – An introduction
=====================
This is fairly basic stuff, University level if you want to call that. If you are a professional developer using C, then you wouldn’t find anything new here and you might be wasting your time. If you are new to C and is struggling to get in terms with pointers, as I have during my Uni days, you might find this helpful.
Okay so let’s get into the topic straightaway.
What happens when you declare a variable, say of type char? This is how you would do it:

char var = 0;


So you have declared a variable of type char, which is a single byte, named ‘var’ and you have initialized that to 0. When you build this code (obviously not just this declaration, with a main function and the necessary header files and all that), the compiler would allocate a memory location say at 0x1234, where the variable ‘var’ would reside.

            0x1234 
     0000  0000

                  
So if you are not going to modify the value of ‘var’ inside the code, this memory location would have the value 0. &var denotes the address where ‘var’ is residing and in this case the value of &var will be 0x1234. If later on in the code we change the value of ‘var’ say,

var    =   10;

then, the memory location 0x1234 will now have the value 10 instead of 0. Whenever you use the variable ‘var’ in your code, the compiler knows that it needs to pick the value sitting in the memory location 0x1234 (Well, only if the variable is still in scope, but lets imagine that we only have a main function in the code and no other sub functions).
            0x1234 
  0000 1010


Now what would happen if ‘var’ was an int? i.e we have made the declaration of ‘var’ as follows:

int var    =   256;

Size of int can vary from system to system. But let’s assume we are using a 16-bit (2 bytes) processor and the size of int is 2 bytes. Compiler will allocate a memory location for ‘var’, say at 0x2345. So what happens when you read the variable ‘var’ somewhere in your code? Would we just need to read the location 0x2345? By declaring as int, we have told the compiler that ‘var’ is now 2 bytes. So the compiler knows that it would need to read both 0x2345 and 0x2346 (it is assumed that the system is big endian in all the examples explained here).
    
     MSB  0x2345 
  0000 0001

        
   LSB 0x2346 
  0000 0000


Now let’s start with pointers.
This is how a pointer is declared:

char *ptr   =   null;

Here, we are declaring an identifier ptr as a pointer of type char.  By doing so, we are telling the compiler that the identifier ptr contains not just a variable – it has a specialty – it is an address! Address of a variable of type char. On building the code, the compiler allocates a memory location; say 0x3456, for ptr to live which currently has a value ‘null’.
Suppose you have the following bit of code in your program:

char * ptr     =   null;
char var       =   10;
ptr            =   &var;

On building the code, let’s assume the compiler allocated the address 0x2345 for var and 0x3456 for ptr. Hence initially, 0x2345 contains the value 10 and 0x3456 contains null. On executing the third line, ptr will change from null to address of var which is 0x2345. Hence, address of ptr (&ptr) is 0x3456 and ptr contains the value 0x2345 which is an address. And what more is, *ptr will give you the value residing in the address 0x2345.
To summarize,
Declaring char * ptr tells the compiler that ptr contains an address.
When you use ptr, you are using the address 0x3456.
When you use *ptr, you are using the value inside the address 0x3456.
The symbol ‘*’ is used to ‘dereference’ the pointer. i.e for finding out what value the pointer holds.

In this case we had a char pointer, which means the pointer points to a variable of type char. Hence when you dereference it, the compiler will know that it has to read a single byte in the address pointed by the pointer. What would happen if the pointer was of type int? Consider the following piece of code:

int * ptr   =   null;

Pointer arithmetic:
==============
This is quite an important concept and quite a useful one when you start writing some serious code in C. Consider the char * ptr case again:

char * ptr     =   null;
char var       =   10;
int ptrVal     =   0;


ptr            =   &var;
ptrVal         =   ptr + 1;

The value of ptr was 0x2345 since we assigned the address of var to it. So what would be the value of ptrVal after the execution of the last statement? The answer is pretty straightforward in this case; ptrVal will be 0x2346 – address of the next memory location.
Now, consider a slightly different scenario:

int * ptr  =   null;
char var   =   10;
int ptrVal =   0;


ptr        =   var;
ptrVal     =   ptr + 1;

Here the pointer is of type int. Again, what would be the value of ptrVal after the execution of last statement? ptr is 0x2345, so ptrVal should be 2345 + 1 which is 0x2346 just as our first case, you might think. Well, it is not. This is pointer arithmetic, so when we are adding 1 (or any other digit) to a pointer, the compiler looks for the address of the next int in the memory location. Since int is two bytes long in our examples, ptrVal will be 0x2347.
Similarly ptrVal + 2 will be 0x2349, ptrVal + 2 will be 0x234A and so on. This was the same in the previous example as well, but since the pointer was of type char, the size of the variable it points to is one byte. Hence ptr + 1 would only be the next consecutive address after ptr, which made it look similar to normal arithmetic.
Will post the next section 'Using pointers' soon!

Tuesday 15 September 2009

Hannan Binth Hashim - Hoax or true story?

This is the latest hot story in the internet - Hannan Binth Hashim, the wondergirl! The whole episode is really so amusing that I just can't believe it and I am going to question the credibility of this story. So if this is indeed true, I owe a big apology to her. It could be also possible that it is partly true and it was exaggerated by some of the bloggers and news papers.

I read it first in the Malayalam daily, 'Mathrubhumi', which is one of the most respected news papers, known for sticking to journalism ethics and all those funky words which one can use when describing a reputed news paper. So when you read any news from such a source you don't have to doubt the credibility of the news; you read it and you take it all, is not? On the first read, I was all praise for the young talent. Questioning Einstein!!?? Doubt the Bing bang theory!! All at the age of 15!!!!! And here is me. I remembered that the video lectures about Special Relativiy theory from a Stanford University professor I downloaded from youtube is still sitting in my laptop. I have not even watched the first 5 minutes of that entire lecture series. Right click -> Properties : 'date created' and 'last accessed' are the same ;-) some six months back! I am the one who couldn't go past the second chapter of 'Brief history of time'. And this 15 year old girl.. My my!! And she is a fellow Indian!! I got goose bumps!! Motivated, I got back to my work, testing my code. Bloody hell!! The processor is still not willing to yield. I spent an hour on the bloody board still with no result. I am not good.. I felt like giving up. Motivation! that is what I need. Hmm, I know an easy source of motivation now, don't I? I opened 'Mathrubhumi' website and started reading the article about Hannan again.

What?? Hold on!! She designed a rocket? And NASA launched it?? Was it not there when I read it last time? Or did I not see it because of the excitement? Now that is unreal! She was supposed to be researching in theoretical physics and astro-physics. What has it got to do with designing space crafts? I read the article again. She graduated from NASA! Well, she is holding the graduate certificate as well. I zoomed in the pic, it says 'Space school graduate'. Googled it; couldn't find anything. The article quotes her mother saying that it took 13 days of exams and experiments and presenting papers at NASA's space school in Houston to achieve that. Okay, so NASA's space school in Houston then, googled again. Wow, NASA do have a space school in Houston. I opened the first link:
The space centre is the official visitor's centre of NASA's Johnson Space Centre in Houston:
So do they have a school where they award graduate degrees? Aha! they do indeed! I read on..
Well well! it doesn't look like a real graduate degree! The space centre is really like an exhibition centre. School students can join for a five day course for a fee, where in they do different team activities - designing rockets etc (nothing too technical as depicted in the numerous Hannan related blogs and articles). And at the end of the school which is after the pre-mentioned five days, they award a certificate of graduation. It is this certificate which the girl (Hannan or who ever really that is) in the picture is holding! I am not certainly getting much motivation here!

I googled for all Hannan related articles. All those come up were from Indian bloggers or some Indian news sites. Some says she has papers presented in MIT, University of Boston etc. Mathrubhumi says she is going to join MIT as a student. So from tenth standard to a graduation in MIT then? I searched the websites of all these universities and NASA where she supposedly has presented papers on Astrophysics. Couldn't find anything about her. Searched in the Siemens Westinhouse Science and Technology Competition site where she is supposed to compete with other students. Couldn't find her details at all. Why am I not surprised now? One last try - searched for Dr. Soumya Vasudevan who is a Hind Rattan winner - Hannan's mentor as described in the article. Wikipedia doesn't list that name among the Hind rattan winners, but that is not really an exhaustive list. So I searched again. Initially when I posted this article the first time, I didn't find any details about her. After some googling I got the details of Dr.Sowmya Viswanathan (note the difference in name), who is a Hind Rattan award winner, but she is a medical practitioner. I also noticed that the 'American Journal of Theoretical Physics' where Hannan's papers are going to get published, never existed.
Hmmm.. I think I will call it a day and test my code tomorrow.
By evening Mathrubhumi has published another news about educational minister calling to congratulate Hannan! What?? Well, I don't know. I am all the more bemused! What is it? A true story or a hoax?