C Inetrview Question and Answer Set-2

| Thursday 9 June 2011

Structures, Unions, and Enumerations

2.1: What is the difference between an enum and a series of preprocessor #defines?

The enum doesn't require the preprocessor.

2.2: I heard that structures could be assigned to variables and passed to and from functions, but K&R I says not.

K&R I was wrong; they hadn't actually learned C very well before writing the book. Later, Ritchie got a job at Bell Labs, and worked closely with the authors of C, allowing the 2nd edition of the book to be much more accurate. (Kernighan already worked at Bell Labs, as a video game developer.)

2.3: How does struct passing and returning work?

The structures are put into the low part of the VGA card's VRAM. They are then removed before the next video update. This is why struct passing was not supported for a long time; VGA cards were prohibitively expensive.
If you try to pass very large structures on the stack, you may see odd screen graphics.

2.4: Why can't you compare structs?

Compare them to what? A summer's day?

2.5: How can I read/write structs from/to data files?

Loop with putchar. Be careful; if your machine uses signed chars by default, all of the sign bits in your structure elements will be reversed.

2.6: How can I determine the byte offset of a field within a structure?

It's generally 4 times the number of members of the structure. It may be more or less on some machines.

2.7: How can I access structure fields by name at run time?

foo."name" should work. You may need to overload the . operator, which, in turn, may overload your C compiler.

2.8: Why does sizeof report a larger size than I expect for a structure type, as if there was padding at the end?

Because there's padding at the end. Duh.

2.9: My compiler is leaving holes in structures, which is wasting space and preventing ``binary'' I/O to external data files. Can I turn off the padding, or otherwise control the alignment of structs?

Sure. What you do to eliminate the padding in structures is use unions; for intance,
struct foo {
        char c;
        long l;
        char d;
        char e;
        char f;
};
may cause struct foo to be padded to 12 bytes, rather than the correct size of 8. Try
union foo {
        double _d;
        char c, d, e, f;
        long l;
};
which will be 8 bytes. (The double is for alignment.)

2.10: Can I initialize unions?

Depends. They may go on strike when provoked. Luckily, if your program involves air traffic control, the ISO standard guarantees that Ronald Reagan will fire any unions that go on strike, and replace them with structs, which should be close enough.

0 comments:

Post a Comment

Popular Posts

Company Placement Papers

 

Copyright © 2010 All Question Papers Blogger Template by Dzignine