[prog] C++ - linked list and segmentation fault
Robert J. Hansen
rjh at sixdemonbag.org
Tue Apr 8 12:25:44 EST 2003
> I was wondering if I could get some advice on a program I am trying to
> complete for class. It is a killer as I am new to linked lists. I write
> the program and it compiles. However, when it runs, it segfaults. I'm
> sure it happens when I am creating the list. All help would be very much
> appreciated.
Free advice: I see from the fact you're using an ifstream that you're
using C++. C++ already has linked lists pre-made for you. Try using
them instead. :)
I'll post again to the list in a bit, showing you how to use the
built-in C++ list class to do what you want done. I'll make sure to
drop lots of breadcrumbs along the way, never fear.
> #include<iostream.h> // for cin & cout
Style:
<iostream.h> is deprecated. <iostream> should be used for all new C++
code.
> #include<fstream.h> // for file i/o
Style:
<fstream.h> is deprecated. Use <fstream> instead.
> struct INVENTORY_ITEM{
> INVENTORY_ITEM *nextItem;
> char itemCode[7];
> int quantity;
> float price;
> }; // end struct INVENTORY_ITEM
Style:
Strictly speaking, this should be called INVENTORY_NODE instead of
INVENTORY_ITEM. Try breaking it up as follows:
struct INVENTORY_ITEM {
std::string itemcode;
int quantity;
float price;
};
Then, to represent a node in a linked list:
struct INVENTORY_NODE {
INVENTORY_ITEM *next, *previous; // doubly-linked list
};
... And if you use the C++ list class, you can do away with
INVENTORY_NODE altogether. As you'll see. :)
--
Robert J. Hansen <rjh at sixdemonbag.org>
More information about the Programming
mailing list