I was reading this link How do I use arrays in C++?, section 5. Common pitfalls when using arrays, where an example is given as following:
// [numbers.cpp]
int numbers[42] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
// [main.cpp]
extern int* numbers;
int main()
{}
Since 'numbers' in numbers.cpp is the name of array, which can normally decay to a pointer equals to '&numbers[0]', I would expect in main.cpp value of 'numbers' is still '&numbers[0]'. But no! it is instead 'numbers[0]', i.e. '1'.
Or let's say I am the compiler, in 'numbers.cpp', I see the symbol 'numbers' as an address pointing to '1', why is this same symbol changed to value 1' in 'main.cpp'?
I understand that's what author says "type-unsafe linking". But I do not know why compiler does this, even if compiler just raise a type-mismatch link error make more sense to me.
Comments
I guess my understanding is, compiler see below as equivalent, so that linker succeed, otherwise will have 'unresolved externals' error:
// [numbers.cpp]
int tmp[42] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; //{1,..9} starts at global address 0x1234
int *numbers = &tmp[0]; //numbers == 0x1234
// [main.cpp]
extern int* numbers; //numbers == 0x1234
int main()
{}
The real situation:
// [numbers.cpp]
int numbers[42] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; //{1,..9} starts at global address 0x1234
// [main.cpp]
extern int* numbers; //numbers == numbers[0] == 1
int main()
{}