Monday, December 3, 2007

Beware the pointer! Arrays vs. Pointers

It's been a long time since one of those 'fundamental' programming ideas bit me. Thankfully, it happened on one of my personal projects, so I didn't reveal to anyone my stupidity.

Errrr... Damn.

Anyway, here was my header file:
extern unsigned int *vectors;

And, here was my (equivalent) .C file:
unsigned int vectors[512];

I was actually mixing languages here. In writing the header, I fell into the trap of thinking pointers are equivalent to arrays. They aren't. The C language creates confusion here because it let's us use array syntax with pointers, and arrays can turn into pointers. We can illustrate this very clearly -

Example 1 .....
char array[15] = { 0 };
printf("%x\n", (unsigned long) array);
printf("%x\n", (unsigned long) &array);


Example 2 .....
char *array = 0;
printf("%x\n", (unsigned int) array );
printf("%x\n", (unsigned int) &array );

Take a look at the output of both programs, and you'll see the exact difference between arrays and pointers. An array without an index is nothing more than a constant pointing to the memory address the array starts at. In a very real way, it doesn't 'exist' as an array, just as a convenience for a block of memory. Here's the breakdown, with this declaration:

char array[15] -

array - is defined as a constant with a value of the address of the start of the array
&array - is the address of the first element

Using an array is a lot like using a statically defined memory address -
char* my_ptr = (char*) 0xB8000;

No comments: