C Programming - Different signature problem with extern variables

One of my friend asked me this question few days back which seemed to be very interesting for me atleast. The question was as follows

File1.c File2.c
1  int arr[80];
1 extern int *arr;
2 int main()
3 {
4 arr[1] = 100;
5 return 0;
6 }

What will be the output when complied and linked together?

It was surprising for me to see a segmentation fault for this kind of a code. Even though array and pointers are different in aspects like
1. Array variable is const pointer
2. Array size has to be defined while declaring the variable

Still I thought array will be manipulated like a pointer, but here in this case what is happening is when we are putting the value 100 to arr[1] it taking the value of the pointer here in this case 0 as arr[80] will be filled with zeros and then adding one to that which mean resulting value will be 0x4 as it is a pointer addition. After that it is trying to put 100 into the address pointed by 0x4 which results in a segmentation fault.

I don't have a sincere justification for this other than explaining why it is working like this. If anyone have any response please post it as a comment.


About this entry