简体   繁体   中英

Combining two structures into new one on C?

So, we have an interesting situation. We are supposed to write a DBMS in C under Linux and we have the following problem: when trying to join two relations/tables the new relation/table has number of Fields/Columns equal to the sum of both joining relations/tables. This is fine, but when we have to copy the data of the tuple/row from the two joining relations/tables we don't seem to find a way. The tuples/rows are realized as list elements via this structure:

typedef struct element {
    void *data;
    struct element *next;
} Element;

The new element is created via this function:

Element *
newElement (void *data)
{
    Element *e = (Element*) malloc (sizeof (Element));
    assert (e != NULL);
    e->data = data;
    e->next = NULL;

    return e;
}

And the *data parameter is passed as of this type:

typedef struct {
    int sid;
    char sname[STRLEN];
    int rating;
    float age;
} Sailor;

The thing is when we have to join two relations we cannot know what Structure they use for their tuples/rows and therefore we cannot create the new tuples/rows for the new relation from the tuples/rows of the two joining relations.

Please help.

Given you cannot at runtime define new structures, something like the following (hack?) could work..

Firstly define a base structure which only has a type id

typedef struct
{
  int type_id; /* this holds a number which identifies the following structure */
} TypeID;

/* now all structures should contain this */

typedef struct {
  TypeID type;
    char sname[STRLEN];
    int rating;
    float age;
} Sailor;

typedef struct {
  TypeID type;
  char sname[STRLEN];
  int sailors;
} Boat;

Now treat the data segment as a container of these structs, let's say for example that I will have two structs in data (ie joined the two above structs), my data segment would look like:

----------
| Sailor |
+--------+
|  Boat  |
----------

When reading the data chunk, first cast it to TypeID , which gives you the type, then you can cast it to the real structure. Then if there is more data in the data segment, move the pointer by the sizeof the structure you've just read, and again do the same process. Basically this allows you to have a variable length segment which is a set of structures of different types - ie your joined data structure.

Oh, and you'll need to modify your Element structure to hold the size of the data segment as well.

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