please leave the subject in the body of your message as well
Subject: "Dynamically and "correctly" allocating memory"
On 29 Aug, 12:23, filia&sofia <in_tyran...@hotmail.com> wrote:
> For example I would like to dynamically allocate memory for linked
> list (or complex struct etc.) that has not maximum number of elements.
perhaps look up linked lists in a data structures book. Or online.
Wiki probably has a good description.
> All that I can remember is that I have to have allocated variable to
> point to the linked list in main program
no. You have to "root" the linked list somewhere, but it doesn't have
to be the main program. It could be inside the library that implements
the linked list or global data. It could be static or dynamic.
> and that I have to have some
> kind of a method that initializes the list (plus other methods to
> manipulate list, of course). "Correctly" means that there should be
> pointers involved,
I'm nor sure how "correctly" implies pointers. Though I'd do it that
way.
> and possibly double or triple pointers.
why?
> I have do
> this long ago, but I just can't remember how to do this neatly... Any
> ideas or links to help me rembember (and yes, I know malloc and
> realloc basics)? Thx in advance.
#include <stdlib.h>
#include <assert.h>
typedef struct node_tag
{
char* data; /* whatever data you want */
struct node_tag *next;
} Node;
typedef struct
{
Node *head;
Node *tail;
} List;
int main (void)
{
List list = {NULL, NULL};
Node *node;
node = create_node("red");
add (&list, node);
assert (find (&list "red"));
assert (!find (&list "blue"));
node = create_node("blue");
add (&list, node);
assert (find (&list "red"));
assert (find (&list "blue"));
node = remove (&list, "red");
destroy_node (node);
assert (!find (&list "red"));
assert (find (&list "blue"));
reurn 0;
}
now just implement the functions above. assert() halts if its
argument evaluates to false (zero).
--
Nick Keighley
"Of course I'm going to be in an aeroplane on 31st December 1999.
You scientists wouldn't be stupid enough to build things that don't
work.
Besides what have computers got to do with aeroplanes anyway?"
(Kerry Nov 199