Friday, March 16, 2007

Did You Know ???

This might sound like an interview question, but very interesting one's, sorry there are 2 questions ;-)

1. Whats the output of the following?

struct a {
char b;
int a;
};
int main()
{
printf("Size of struct a is %d\n", sizeof(struct a));
return 0;
}

Ans: Assuming int = 4 bytes, size will be 8 bytes.

Ok, now the real question, how do you make "sizeof(struct a)" to print 5 bytes,
which is the actual size of structure.

Solution ;-),just add a line to direct the compiler using pragma.

#pragma pack 1
struct a {
char b;
int a;
};
int main()
{
printf("Size of struct a is %d\n", sizeof(struct a));
return 0;
}

Now, check out the output, it says 5 bytes !!!

2. Run a program without a main() function in it ??
Please, don't google for it, just look below ;-)

By the way, I tried this only on HP-UX,
so please try out on different OS, post it in comments.
Basically, you need to do "man cc", to check out the
compilation option.

#vi t.c

int f1()
{
printf ("Hello world\n");
return 0;
}

# cc t.c -o t -ef1
Warnings: Are meant to be ignored by programmers ;-)
# chmod +x t
# ./t

Aila, it's running !!!

1 comment:

Shantanu said...

I used sunstudio compiler
1) I had to use #pragma pack(1)
2) Did not compile
test@shantanu>cc t.c -o t -ef1
Undefined first referenced
symbol in file
main
ld: fatal: Symbol referencing errors. No output written to t