Alcatel Lucent Interview Question
Software Engineer / DevelopersCountry: India
Interview Type: In-Person
1. Declare array of the type X of size 2
2. subtract address of 1st elemement x[0] from 2nd element i.e. x[1]
this will give you size of X
Almost, first convert the two pointers to char *, otherwise you will get 1 (this is how pointer arithmetic works)
X array[2];
char *first = (char*)array; // which is &array[0]
char *second = (char *)(array+1) // which is &array[1]
return second - first;
This works because sizeof (char) is defined as 1, and it is one of the very few implementation dependent type sizes in C.
Well, one could argue that an array of type X is not a variable of type X. One could counterargue, however, that creating an array of type X implicitly creates a pointer to type X.
Create an array of two elements, subtract the addresses of second element from first element. Working code:
#include <iostream>
class X{
public:
int i;
int j;
bool k;
int l;
int q;
int* n;
double* m;
};
int main(){
X A[2];
size_t addr1 = reinterpret_cast<size_t>(&(A[1]));
size_t addr0 = reinterpret_cast<size_t>(&(A[0]));
size_t size = addr1-addr0;
std::cout << size << std::endl;
}
if you don't reinterpret cast, size would always give 1 due to pointer arithmetic.
char dummy[10]; // X is data type of unknown size
- Abhi February 02, 2012int size=(X *)dummy[1]-(X *)dummy[0];