"C" Programming Language - Structures, Unions, and Enumerations

Started by sivaji, Jan 10, 2008, 07:15 PM

Previous topic - Next topic

sivaji

Programming Stuffs in "C" - Technical Skills for INTERVIEW

Structures, Unions, and Enumerations


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

The enum doesn't require the preprocessor.

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.) [

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.

4: Why can't you compare structs?

Compare them to what? A summer's day?

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.

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.

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.

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.

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.)

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.

11: How can I pass constant values to routines which accept struct arguments?

Try foo((struct foo) 3).
Am now @ Chennai