Comment

created: 1/20/2007; revised: 06/29/2017

Puzzles T21 ... T30

Part T — Struct Problems

These puzzles involve structs and pointers.

A variable may:

  1. be the actual memory of a struct, or
  2. may contain a pointer to a struct.

Here are the two possibilities:


pointer vs direct
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.



Next Page         Home