Dynamic Memory Allocation
The only way to get dynamically allocated memory
is via a system call (which is generally via a
GNU C Library function call), and the only way to
refer to dynamically allocated space is through a
pointer.
For example, if you want to allocate dynamically
some space to hold a struct foobar
, you cannot
declare a variable of type struct foobar whose
contents are the dynamically allocated space. But
you can declare a variable of pointer type
struct foobar *
and assign it the address of
the space. Then you can use the operators ‘*’ and
‘->’ on this pointer variable to refer to the
contents of the space:
{
struct foobar *ptr = malloc(sizeof *ptr);
ptr->name = x;
ptr->next = current_foobar;
current_foobar = ptr;
}