Accenture Interview Question
Software Engineer / DevelopersTeam: dx
Country: United States
I think output for all four cases will be 1.
In C difference between two addresses of same data type is usually 1, because addresses for memory is allocated to variable from heap memory.
And thus the difference between two consecutive addresses is 1
The answer I get from my compiler is 3, 3, 12, and 2. The C Standard makes no guarantees about packing of local variables. Moreover, as for subtracting two pointers the Standard states "Unless both pointers point to elements of the same array object, or one past the last element of the array object, the behavior is undefined." So, we have undefined behavior. And don't get me started on "void main".
The reason for 1 is , in C the pointer will be incremented always by the size of pointer type, for example if the pointer type is int and size of int is 4 bytes, and you increment the pointer it always increment the pointer by 4 bytes, and similarly if you do addition or subtraction it is always %sizeofpointer, in this case it's %4.
This below example gave me bit clarity.
#include<stdio.h>
main()
{
int arr[2]={10,20};
printf("%0x\n",&arr[0]);
printf("%0x\n",&arr[1]);
printf("%d\n",(char*)&arr[1]- (char*)&arr[0]);
}
The result might be compiler/platform specific. I think that there's no any warranty that the compiler will put local variables on 2 sequential adjacent addresses.The difference would be 1 if a and b were elements of the same array, for local two local variables the result might be surprising.
- Fan March 29, 2013