Interview Question
Country: India
If it is as in the example then there is no problem at all.
IF int arr[10]; would be a const array than the write access could fail - based on the operating system and memory allocation of the C compiler.
For me using gcc in ubuntu, this is giving seg fault. And when I comment arr[0]=10 in file2 & print arr in file1 & (&arr) in file2, I get the same address. So, I guess the *arr in file2 is linked to &arr in file1 though in file1, arr and &arr are same. I don't know if it is compiler dependent..
You will get linker error!
- words&lyrics July 18, 2012Compiler only looked for names for binding not the type so int *a was binded to int a[] (basically that means both a have same address). If you try to print '&a' in file 1 and '&a' in file 2 you will get same address. so both the pointers are at same location.
So basically binding is some what like this
&a = &a; instead of a = a
Although the pointer addresses are same the content at the addresses ('a ' not *a )) is not. In first case it was the addresses of first element of array (const int*) , in second case it is NULL. Why it is happening is something , that can be attributed solely to compiler architecture . Here what is happening is , a const int* cannot be converted into int* so the compiler decides to Make it NIL.
This will work;
file 1: char* a =&('a')
fil2 2; extern int *a;
print *a; //off course with %c to avoid memory infringement
because char* can be type casted to int*
In your example even access to *a is in valid as it is essentially Null.
My final conclusion is may be on different compiler the results will be diffrent as it is clearly upto compiler how to handle.