top/contents search

2. Structures, Unions, and Enumerations

2.1 What's the difference between these two declarations?

	struct x1 { ... };
	typedef struct { ... } x2;

2.2 Why doesn't

struct x { ... };
x thestruct;
work?

2.3 Can a structure contain a pointer to itself?

2.4 How can I implement opaque (abstract) data types in C?

2.4b Is there a good way of simulating OOP-style inheritance, or other OOP features, in C?

2.5 Why does the declaration

extern int f(struct x *p);
give me an obscure warning message about ``struct x declared inside parameter list''?

2.6 I came across some code that declared a structure like this:

struct name {
	int namelen;
	char namestr[1];
};
and then did some tricky allocation to make the namestr array act like it had several elements, with the number recorded by namelen. How does this work? Is it legal or portable?

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

2.8 Is there a way to compare structures automatically?

2.9 How are structure passing and returning implemented?

2.10 How can I pass constant values to functions which accept structure arguments? How can I create nameless, immediate, constant structure values?

2.11 How can I read/write structures from/to data files?

2.12 Why is my compiler leaving holes in structures, wasting space and preventing ``binary'' I/O to external data files? Can I turn this off, or otherwise control the alignment of structure fields?

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

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

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

2.16 Does C have an equivalent to Pascal's with statement?

2.17 If an array name acts like a pointer to the base of an array, why isn't the same thing true of a structure?

2.18 This program works correctly, but it dumps core after it finishes. Why?

	struct list {
		char *item;
		struct list *next;
	}

	/* Here is the main program. */

	main(argc, argv)
	{ ... }

2.19 What's the difference between a structure and a union, anyway?

2.20 Can I initialize unions?

2.21 Is there an automatic way to keep track of which field of a union is in use?

2.22 What's the difference between an enumeration and a set of preprocessor #defines?

2.23 Are enumerations really portable?
Aren't they Pascalish?

2.24 Is there an easy way to print enumeration values symbolically?

2.25 I came across some structure declarations with colons and numbers next to certain fields, like this:

struct record {
	char *name;
	int refcount : 4;
	unsigned dirty : 1;
};
What gives?

2.26 Why do people use explicit masks and bit-twiddling code so much, instead of declaring bit-fields?


top

contents search
about this FAQ list   about eskimo   search   feedback   copyright

Hosted by Eskimo North