Wednesday, November 08, 2006

Introduction What's array

A basic definition of an array would be: A collection of items of the same type, where each item has assigned a index number. Sounds simple enough, but in order to take advantage of it, we must get past this definition and enter the dark side of it: How arrays are stored in memory.

A Little Foreplay Is Always Necessary, As They Say

For me to successfully explain this concept, I must mention a little something about RAM, or the computer memory. RAM is linear. This means it is not layed out in some complex two or three-dimensional or n-dimensional form or something of that sort. It is very simple: The first byte is followed by the second byte, which is also followed by the third byte, and so on. All the bytes available in RAM are one next to the other. No special directions to reach a particular byte are needed. You just say byte 0, byte 1, byte 65536 (the first byte after the first 64Kb of memory). All you have to do is count from the first byte to the byte number given.

The numbers I just presented above are to be considered memory pointers. If you have a variable pointing to byte 65536 and the data stored there is a long value (4 bytes), then the next available RAM space is at byte 65536 + 4 = 65540 (plus four because a long value requires 4 bytes). Normally, you will see pointer values written in hexadecimal format. It is the same thing, but Hex is preferred because of its compact mode, among other few advantages.

Working with pointers is somewhat simple, but not so simple for VB programmers. You see, math for pointers require that the pointer variables do not reserve the most significant bit for the sign, and that variables holding pointers must be 4 bytes long. Why this? Simple really: There are no negative byte counts. You never refer to a byte as byte -30; there is just no such thing. This is why you should always be very careful when using a pointer to get another pointer by adding an offset of bytes. As a general rule of thumb, you should never do this calculation except for positive pointers while working in VB.

No comments: