created: 1/20/2007; revised: 06/29/2017
These puzzles involve structs and pointers.
A variable may:
Here are the two possibilities:
typedef struct { int watts; int lumens; } Bulb; int main () { Bulb direct = {100, 1710}; Bulb *reference; reference = (Bulb *)malloc( sizeof( Bulb ) ); reference->watts = 40; reference->lumens = 850; . . .
The variable direct
is the name
of the actual memory of a struct.
The variable reference
holds a pointer
to a struct.
The declaration
Bulb *reference;
merely sets up the variable reference
without
putting any value in it.
No memory is allocated for a struct.
At run-time, the program allocates memory for a struct:
reference = (Bulb *)malloc( sizeof( Bulb ) );
The sizeof()
operator determines the number of
bytes needed.
At runtime, malloc()
asks the operating system
for that many bytes and returns the address of the first byte
of the block.
A type cast (Bulb *)
tells the
compiler how the address will be used.
So there are two ways to access a struct — directly and by reference (through a pointer). This can be confusing.