NVIDIA Interview Question
Software Engineer / Developers#define __SIZEOF(x) \
({ \
struct { \
typeof(x) y; \
char c[0]; \
} __attribute__((__packed__)) s; \
(size_t) (&((typeof(s)*) 0)->c); \
})
// __SIZEOF(void) gives an error
plz explain the last line
"(size_t) (&((typeof(s)*) 0)->c)"
and what does "__atribute__((__packed__)) s" do? is it related with padding?
"(size_t) (&((typeof(s)*) 0)->c)" gives the offset of char c[0] in the structure s. Effectively, the offset of char c[0] in structure s is the sizeof(y) i.e. the required size.
"__atribute__((__packed__)) s" is actually not required. But if put, the sizeof structure s will be exactly equal to the sum of sizes of the members in that structure without any memory alignment.
sizeof (char* type){
void *p;
map <char[ ], int> my_map ;
my_map["int"] = 1;
my_map["char"] = 2
my_map["float"] = 3;
.
.
.
switch(my_map[type]){
case 1 :
{
p = (int*) malloc(1);
return ((int*) &(p+1) - (int*) &p) ;
}
case 2 :
{
p = (char*) malloc(1);
return ((char*) &(p+1) - (char*) &p);
}
.
.
.
.
and so on
}
#define my_sizeof(type) \
- GhostArcher September 23, 2011({typeof(type) x; (char *)(&x+1)-(char*)(&x);})