struct node *root, *currentNode;
root = (struct node*)malloc(sizeof(struct node));
root->value = '\0';
root->next = 0;
currentNode = root;
2 Answers
What does the following code in Morse Code Arduino mean?
Step by step:
struct node *root, *currentNode;
Pointer variables root
and currentNode
. Pointers to struct node
.
root = (struct node*)malloc(sizeof(struct node));
Allocate memory for a struct node
and assign root
pointer.
root->value = '\0';
root->next = 0;
Assign struct node
members using the root
pointer. Assign value
member to character 0. Assign next
to zero, NULL, i.e. often marks end of list.
currentNode = root;
Last assign currentNode
to point to the save value as root
, i.e. the allocated struct node
.
Next question?
What's missing from this tiny code excerpt is the definition of 'struct node'. From the name, 'node', the member name, 'next', and the way these are being assigned, it's very likely that these 'struct node's are part of a linked list structure; a collection of data that is arranged, not by location as in an array, but by each node having a pointer (memory address) to the next one in sequence. One fixed memory location (apparently 'currentNode') points to the first datum; that one points to the next, and so on until the last one in sequence whose pointer value iz zero (or NULL, the symbol commonly used for an invalid pointer value).
Sorting a list is quicker than sorting an array or a collection of arrays of data, because only the pointers need to be changed; no data needs to be moved. Adding or deleting data in the middle of the list benefits even more; in an array you'd have to move all of the data following the add- or delete-point to create or close a gap for the new or removed datum.
Look at the rest of the code. It's quite likely that is how the 'node's are being used. Also read about linked lists, if that is a new concept.
node
and initialize it - then copy the contents to another local variable calledcurrentNode
.currentNode->value='a';
thenroot->value
becames'a'
too, as it is on the same place in memory. (until you moveroot
orcurrentNode
to poit to other place - I would bet, that somewhere else is command likecurrentNode=currentNode->next;
)currentNode
wasn't a pointer, but a local variable.