2.1 C

In C, there is no class. There is only struct, which serves about the same purposes. Let us look at the definition of a named struct:

struct X
{
  int i;
  float f;
  char a[20];
};

This defines a record type that has three members, i, f and a. Now, let us consider the following block of code:

{
  struct X myX;

  printf("%d %f %s\n",myX.i, myX.f, myX.a);
}

This block of code attempts to print each member of variable myX. Note that because myX is defined in a block, it must be a local variable. Without a static keyword, it is also an auto variable.

Upon entry of this block of code, some memory is allocated for myX. However, the memory locations are not initialized. The individual bytes allocated to myX most likely contain bit patterns that do not make any sense.

As a result, as we attempt to print the members of myX, garbage is expected. In fact, when the string is printed, the program may even crash, or print out something that can mess up the configuration of a terminal.

An auto structure in C must be initialized explicitly before it can be used.

Copyright © 2006-09-05 by Tak Auyeung