extern arrays and pointers Saturday 17th November 2007
Quick, what’s the difference!
extern char data[];
extern char *data;
Well the first one’s and array and the second one is a pointer. You can treat them in the same way, but they are completely different things.
Here’s a function which looks the same with both declarations of data:
char f(int a) { return data[a]; }
But if data is an array it compiles to the following. (gcc -O3 -fomit-frame-pointer)
f: # move the function parameter from the stack into $eax movl 4(%esp), %eax # access the byte at data + $eax and store into $eax movsbl data(%eax),%eax ret
And if it’s a pointer it compiles to this.
f: # move the pointer value at the memory location data into $eax movl data, %eax # move the function parameter from the stack into $edx movl 4(%esp), %edx # access the byte at $edx + $eax and store into $eax movsbl (%eax,%edx),%eax ret
It’s an easy enough mistake to make but I find it unintuitive the way that the change in external declaration silently changes the effect of the function without any change to the function definition itself.
It’s important to get external declarations consistent and this can be a problem if the array data lives in a non-C (or non-C++) file, e.g. test data included via an assembly file.