C Programming Examples
- hello, world which also
illustrates conditionals, variable declaration, and simple text I/O
- use_up_mem.c illustrating the
declaration of pointer variables, dynamic memory allocation, and the
perils of memory leaks (the program eventually halts when it runs out of
memory). Note that the analogous program written in Java never
runs out of memory, because the memory allocated in one pass through the
loop becomes unusable on the next pass and is therefore automatically
recycled.
- io.c illustrating the
fgets
function. Note that fgets
takes an int parameter telling
how large the buffer is; the simpler gets
function doesn't,
so if the user types something too long, it stomps over whatever happens
to come next in memory, leading to nonsense variable values and/or
crashing or freezing programs.
- file_io.c illustrating standard functions
for reading from files (there are analogous functions to write to files)
- strcat_ex.c illustrating some common
tasks with strings: concatenating strings, initializing strings,
extracting parameters from the command line.
- array_ptr_0.c illustrating the
differences among pointers to pointers, arrays of pointers, and arrays
of arrays (i.e. multi-dimensional arrays)
- struct_1.c illustrating the declaration
and use of structs
- typedef_2.c illustrating making up new,
convenient names for old, complicated types with
typedef
- union_3.c illustrating
union
,
a way of intentionally treating the same region of memory as two or more
different types at different times. Dangerous, but can be useful.
- union_4.c illustrating
union
s
with discriminator variables, so you can keep track of which type the
variable "really" is. Note: the language doesn't enforce this; the
responsibility is entirely on the programmer.
- enum_5.c illustrating the use of
enum
to define groups of symbolic constants with distinct
values (typically when you don't care what the values are).
- Pets, a miniature example of writing a program
spread out over several source and header files.
Last modified:
Stephen Bloch / sbloch@adelphi.edu