简体   繁体   中英

2 struct using 1 pointer in C

I am working on my linked list project in C, but I'm having some difficulty using 2 structs with only one pointer.

Example like this

struct makanan
{
    char nama [50];
    char nama_menu[50];
    float qty;
    int jumlah_bayar;
    int nomor;
    int harga;
    struct makanan *next;
    struct makanan *prev;
};
struct makanan *head;
struct makanan *bantu;
struct makanan *tail;

//menu's declaration
struct menu_makanan
{
    int harga;
    char nama_makanan[50];
};

Since my teacher said that must used at least 2 struct in this program, I want to ask:

  • How can *head , *bantu , *prev and *next be used in struct menu_makanan ?

Given that a menu ( menu_makanan ) should contain a list of items ( makanan ) in some shape or form, and given that makanan contains the pointers to make a list, it seems logical that you should be using:

struct menu_makanan
{
    int harga;
    char nama_makanan[50];
    struct makanan *head;
};

The harga member could hold a count of the number of items in the list pointed at by head , or it could be some other value (since the length can be derived on demand if need so be).

If you wish, you could add a struct makanan *tail; member to menu_makanan too.

Now the global variables head and tail are redundant; that's usually a good thing. Avoid global variables when you can. Since I'm not sure what bantu does, I can't tell whether that's redundant too, but there's a moderate chance it is, or can be made, redundant too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM