Both pointers will need to be set to something. name
must either be set to point to a string literal, an array of char
, or a chunk of memory returned from malloc
or calloc
or realloc
. itself
will need to be set to another instance of struct node
. Whether you need to use dynamic allocation or not depends on what you're trying to do.
In a singly-linked list, the itself
pointer will hold the address of another instance of struct node
. You can picture it as something like the following:
+---+---+ +---+---+ +---+---+ +---+---+
| | |--->| | |--->| | |--->| | |---0
+---+---+ +---+---+ +---+---+ +---+---+
| | | |
| | | |
V V V V
+---+ +---+ +---+ +---+
|'f'| |'b'| |'b'| |'b'|
+---+ +---+ +---+ +---+
|'o'| |'a'| |'l'| |'l'|
+---+ +---+ +---+ +---+
|'o'| |'r'| |'e'| |'u'|
+---+ +---+ +---+ +---+
| 0 | | 0 | |'t'| |'r'|
+---+ +---+ +---+ +---+
|'c'| |'g'|
+---+ +---+
|'h'| |'a'|
+---+ +---+
| 0 | | 0 |
+---+ +---+
We have 4 instances of struct node
. The name
members of four of them are pointing to strings, and the itself
members of three of them are pointing to other instances of struct node
.
Now, whether the strings or other node instances are dynamically allocated or not depends on your program. You can allocate an array of struct node
and have each element explicitly point to the next one in turn:
struct node nodes[N] = {{NULL, NULL}};
for ( size_t i = 0; i < N-1; i++)
nodes[i].itself = &node[i+1];
You can set each node to point to an already-existing array of char
or a string literal:
char buffer[] = "foo";
node[i].name = buffer;
node[j].name = "blah";
Alternately, you can allocate everything dynamically:
/**
* Adds a name to the head of a list
*/
void pushName( struct node **head, const char *name )
{
struct node *newNode = malloc( sizeof *newNode );
if ( newNode )
{
newNode->name = malloc( strlen( name ) + 1 );
if ( newNode->name )
strcpy( newNode->name, name );
newNode->itself = *head;
*head = newNode;
}
}
...
struct node *list = NULL;
pushName( &list, "blurga" );
pushName( &list, "bletch" );
pushName( &list, "bar" );
pushName( &list, "foo" );
which gives us something like the diagram above.
It all depends on what you're going for.