Adi Drumea

Friday, June 03, 2005

[C/C++] Arrays and pointers

Recently, during a Compilers test at school, I stumbled across a question like this: "You are given two modules. In module A you have the definition 'int a[100];'. In module B you have the external declaration 'extern int *a;'. Does this link properly?" Pointers and arrays are simiar in C/C++ but not identical. My answer was something like... well you are trying to map a pointer over an array, it should not even link. When I tried this in VC++/GCC, it linked without complaining. But, I have an example why this is not always correct:

a.cpp:

#include
int a[100] = {1, 2, 3};
void f() { printf("%d\n", a[0]); }

b.cpp:

#include
extern int *a;
void main() { int x = 10; a = &x; printf("%d\n", a[0]); f(); }

In the above example, the problem is caused by the a = &x statement. The linker maps the pointer to the array defined in a.cpp. This statement replaces the first element in the array a with the address of x (because sizeof(int) == sizeof(int *) on 32 bit). Running the example above, will print the number 10 and then the address of x.

Conclusion: avoid re-declaring arrays as pointers in external declarations, it can have unexpected behaviour as shown above.

0 Comments:

Post a Comment

<< Home