Originally Posted by
zub
I find it easier to write code than to explain, because English is not my native language.
Ah. Don't worry, the idea is to highlight things that the the help seeker might miss. You don't have to have perfect English to do that.
Originally Posted by
zub
Moreover, in this particular case, no explanation needed. Compare line by line and you will understand what I have done fixes.
It is not always reasonable to expect a newbie to be able to distinguish between changes that are substantially important, those that are important stylistically, and those that are merely subjective style, just by reading code.
Originally Posted by
zub
I can further simplify the code with a few useful tricks. Good code is self-evident and self-documenting.
Unfortunately, your typedef of struct Node* to be Node makes code involving Node no longer self-evident, and your NEW function-style macro is not self-documenting since it relies on the macro argument being of a struct type. Compare:
Code:
Node i = NEW(Node);
i->data = 34;
with:
Code:
struct Node *i = malloc(sizeof(*i));
i->data = 34;
In the former, one must already be familiar with the NEW macro and know that for NEW(Node) to work the type struct Node must exist; accessing i->data is surprising since Node does not appear to be a pointer. In the latter, the reader is likely to be familiar with malloc and sizeof, and i->data is not surprising since i is obviously a pointer.
Instead of a NEW macro, I would suggest a function for creating and initialising the node, e.g.,
Code:
struct Node *node_init(int data)
{
struct Node *node = malloc(sizeof(*node));
if (node)
{
node->data = data;
}
return node;
}
This can then be called in main with no loss of clarity, e.g.,
Code:
struct Node *i = node_init(34);
Originally Posted by
zub
By the way, I forgot to free memory. All the time I forget it, because my own projects use my own allocator, which does not require this.
That's fine: gaurav#'s code made the same mistake, and we are certainly not responsible for pointing out all possible mistakes in code posted by someone asking for help.