Hewlett Packard Interview Question
Country: India
Interview Type: In-Person
yes, u r correct. It compiles, and I fortunately was able to revert my answer during the interview to say yes, it will compile :P but wasn't sure.
But, Its not overwriting the previous argument..for instance
char a, b[10];
then b[-1] shouldn't overwrite a for a function stack??
yeah it even compiles if you write it "upside-down", i.e.
(-1)[a] = 4;
because for the compiler a[i] and i[a] are semantically the same))
Good Question..
Lemme Tell ya...
1> It will compile and run . I swear there will be NO crash as well. By that what I mean is C/C++ unlike Java Does NOT have bound check for arrays. So than what will happen to the value ??
Here it goes .. basically it will depend on OS but basically here what the compiler calculates: (base address of array a - datatype of array a). so here if a is 1000 and assuming 32 bit compiler , value of 20 is going to be stored at logical address 1000-4 i.e. 996.
I did this in my cent os,
int main()
{
int a[20];
int i = 9
a[-1] = 4;
printf("%d",i);
return 0;
}
So it printed 4, it will not work if i exchange the declaration of i and a[], you can check by printing the memory addresses.
that's nice. Actually this is what I answered him, and was 100% sure, this should happen, but on my DevC++ windows IDE, i wasn't seeing this happening.
Maybe, I will boot with unix and try it.
Thnx for confirming.
the program will definitely compile, but the behaviour is undefined. why here is the reason.
declaration int a[10] // it allocates 40 bytes and suppose 1000 is the starting address.
a[-1]=10 // access memory location 996 and put 10 at this location.
but we are not sure whether 996 memory location is read only ,part of stack, part of code segment.
if it is read only,part of stack or part of code segment, then surely we will get error like segmentation fault or access violation.
One of my professors was talking about this. He basically said that the prefix to an array is made up of the size of the array. So basically at a[-1] there exists a variable that has the size of the array. So that is where you would be writting to. Please double check this, this is just what I remember from last quarter.
I am not sure where it won't compile. It works fine on codepad!
- Laxmi Narsimha Rao Oruganti November 22, 2011Code: h t t p://codepad.org/IzbqB7Mc
a[1] translates to *(a + 1).
a[-1] translates to *(a - 1).
In words: value at (base address of array 'a' minus a integer size).
By all means, it should compile. However, at runtime one might hit segmentation fault/acces-violation if the address does not belong to this thread. But, array is a local variable in this case inside function main. Which means, the allocation of array 'a' is on the stack. Minus four bytes just takes to the call stack frame of function main. So, in most cases you get unpredictable value (and may not really hit AV/SegFault).
Thanks,
Laxmi