> Did you allocated the memory needed by the data element pointed to by the
struct pointer ?
>
> Ie :
>
> typedef struct _s
> {
> int x,y;
> struct -s *next=NULL;
Typo: struct_s *next = NULL, right?
> }
>
> struct_s foo;
> struct_s bar;
Remember this line...
>
> If you wish to make the foo.next elemnt to point to bar, you must :
>
> foo.next=(struct _s*)malloc(sizeof(struct _s));
> foo.next=bar;
In what you do here, you're overwriting the pointer to the memory allocated,
causing a memory leak.
It's like saying:
b = 25;
a = 35;
a = b;
That's dangerous and unnecessary, since `bar' is already allocated on the
stack on the line marked. So you would just have to say
foo.next = &bar;
Only if `bar' is a pointer would you do this:
struct_s *bar;
bar = new struct_s;
foo.next = bar;
Regarding the original problem, of filling up a pointer to a struct, it
would be like this:
struct_s *foo = new struct_s;
foo->value = 25;
This will not cause a crash (provided `new' allocated).
Also note that `malloc' is considered dangerous (since it doesn't call the
constructor), and only `new' should be used. However, for allocating buffers
(of chars, etc.), I find it better to use malloc() and realloc().
One more thing, it's always better to initialize all pointers to NULL, so
that any error in your code will result in an immediate crash with a
NULL-pointer error, rather than a hidden bug that'll surface on the other
side of the program and make debugging a nightmare.
|