Posts Tagged ‘object oriented’

C to Java

November 17, 2011

Well it is not an advanced topic by any means, just a place to recall some jargons of these languages (C, C++ and Java). This might be part one of two posts in a series. Some of the topics I haven’t covered are related to Generics, String, Networking, I/O (Even Google’s I/O), Concurrency etc. This post is a starter, yet complete on its own respect.

1. In C starting point is off course pointers.

What is a pointer?
A pointer is a variable that can hold the address of a variable. Here address means location in memory where the object or value of a particular variable is stored. We can get address of any variable with “&”.

E.g
int x = 5;
int *ptr = &x;

/*
int *ptr;
ptr = &x;
*/

int y = *(&x);
y = *ptr;

Lets look at above example. First we create a variable called x and gave it a value of 5. The variable can be located anywhere in the memory, the location which we don’t know. Next we create a pointer to integer called *ptr and put the address of variable x into it. Thus ptr is a pointer (a variable that can store an address). If this line makes no sense next line dissects it into two steps. First we create a pointer to integer with int *ptr and then put address of x (which we get using &x) and put it in ptr pointer. Next we create another variable y and dereference (return object or value) that is at address of x using the dereferencing operator * (don’t confuse this with our earlier pointer declaration as in int *ptr, both are different).

A pointer is thus a variable which is always the size of the underlying architecture (it does not depend upon the type of variable e.g int, char or double, because address size of first block to any of these types is same), though pointers are aware of the type they are pointing. They must know how much bytes they must occupy according to the type. E.g if integer takes 4 bytes (32-bit) and char takes 1 byte (8-bit) then if ptr is pointer to integer *(ptr + 1) will give value of next pointer location which could be four bytes ahead of current value and if ptr is pointer to  char, then it might need to go only one byte ahead to get value of next consecutive memory location.
(more…)