Sunday, July 29, 2007

Quick Tip: Basic Guide to Pointer Arithmetic

The use of pointers is often improperly used in the world of C/C++ coding and usually takes budding programmers time to understand how to use them. This is why pointer arithmetic is usually avoided like its some weird phobia.

So here is a quick tip to help you keep your head on straight when thinking about these operations. When you declare a pointer such as unsigned char* pData =NULL; you'll have effectively declared a variable that has the value of an address, in this case a NULL address. Now when performing operations such as pData++ you are adding 1 to that address value meaning your pData now points to an address of 0x1 or 1 from the start address. Simple right?

Well this is the part that most people tend to forget the operators work on the
address values, but the value contained in that address is based on the pointer primitive type. So in our current declaration of pData we can only move one byte (unsigned char == 1 byte) at a time when performing the operation pData++ . So if our pointer had the primitive of an unsigned short int (unsigned 16 bit value) then the operation would move in 16-bit chunks, this is very important to note when dealing with data parsing. It's really straight forward but you'd be surprised how often people forget/just don't know how this works.

No comments: