A structure is a collection of variables.
Define a structure type as in this example.
struct cell { int n; struct cell* next; };Notice the semicolon at the end. Also notice that the type is called struct cell, not just cell.
C allows you to create a structure either in a stack frame (as an automatic variable) or in the heap. (In Java, you can only create an object in the heap.)
Statement
struct cell c;creates automatic variable c of type struct cell. Statement
struct cell* p = (struct cell*) malloc(sizeof(struct cell));creates allocates one cell in the heap and stores the address of the allocated cell into automatic variable p.
Type definition
typedef struct cell { int n; struct cell* next; } CELL;defines type struct cell and makes CELL another name for it. Now you can write
CELL* p = (CELL*) malloc(sizeof(CELL));
To select a variable from a structure of type CELL, use a dot, as in Java. So if c has type CELL then
c.n is the variable called n in CELL c.
c.next is the variable called next in CELL c.
To select a variable from the structure pointed to by a given pointer, use -> instead of a dot. If p has type CELL* then
p->n is the variable called n in the CELL to which p points.
p->next is the variable called next in the CELL to which p points.
Define a constructor as an ordinary function. Do not try to write it inside the structure type definition. For example,
CELL* newCell(int m, CELL* q) { CELL* p = (CELL*) malloc(sizeof(CELL)); p->n = m; p->next = q; return p; }
defines constructor newCell. Notice that it actually returns a pointer to a CELL. See the next item.
A structure is similar to a Java class, but with heavy restrictions. There are only variables. There are no instance methods or static methods associated with a structure.
All of the variables are public. There are no static variables.
But, once you accept those restrictions, you can imagine a value of a structure type to be similar to a Java object.
Java stores all objects in the heap. Unless you are sure that an object is only needed during a call to the function that creates the object, you would do well to use the same principle. Allocate objects in the heap. Refer to them by pointers.
See linkedlist.h and linkedlist.c for a vey small definition of linked lists.