Re: pointers to structs
Date: 14 Jul 2004 23:10:16 GMT
John Hanley <firstname.lastname@example.org> wrote:
> I am creating a linked list for a DOS program. I have 2 structs:
> struct data_record
> struct data_record * next;
> struct data_list
> struct data_record * head;
> struct data_record * tail;
> int main()
> struct data_list * list;
Here you define a pointer to a structure data_list. But that pointer
points to nothing you "own" yet, just to some completely random location
> list->head = NULL;
And here try to you assign a value to a member of zhe structure that
doesn't exist yet.
> list->tail = NULL;
And here again, of course.
> When I compile then run this, I get: "Exiting due to Signal SIGSEGV. Page
> Fault at ..."
> Can I not assign NULL to these pointers? If I take the 2 assignments out,
> it runs ok.
Well, then there's nothing left of your program;-) Problem is that
you don't assign to the pointer ('left') but to what it's pointing to.
But it's not pointing to anything useful yet. At the moment it just
points to some random location in memory. Before you can assign to
something via the pointer (and that is what you try to do when you
write "list->head = NULL;") you first have to make 'list' point to
some memory you own. There are basically two ways to make 'list'
point to to some "real" memory, i.e. memory you own: 1) define a
structure and assign its address to 'list' or 2) call malloc() to
ask the operating system to give you some memory and then assign
the return value to the pointer.
Your program would work quite fine if you wouldn't use a pointer
but a "real" structure:
int main( void )
struct data_list list;
list.head = NULL
list.tail = NULL;
but I guess that's not what you're looking for (I guess you're
trying to create a linked list and then you have to deal with
pointers, but also with the methods of obtaining memory for the
elements of the list...)
-- \ Jens Thoms Toerring ___ Jens.Toerring@physik.fu-berlin.de \__________________________ http://www.toerring.de