--- In [email protected], Ravi Mishra <ravics...@...> wrote:
>
> I have a question regarding struct when making Table eg.

C or C++?

Basically your types X/Y/Z should contain pointers to the list data, so the 
data does not actually reside within the table structure itself. Hence the 
lists can grow without overwriting other fields within the table.

In C++ (which isn't my language) there are Standard Library list types which 
you can use. In C you don't get any standard list types, but there are plenty 
of implementations out there that you can use.

Here's a very simple C program that constructs a list from any number of values 
passed on the command line and prints them out. It makes use of the realloc() 
function to grow the list dynamically. Note that the list structure only 
contains a pointer to the data, and not the data itself.

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>

/* List structure. */
typedef struct List_s
{
    int *a; /* pointer to the data a[0..n-1] */
    int  n; /* size of list */
} List_t;

/* Initialise the list. */
static void listInit(List_t *list)
{
    list->a = NULL;
    list->n = 0;
}

/* Add the value to the end of the list. */
static void listAddEnd(List_t *list, int val)
{
    /* First increase the size of the list by 1. If the value of list->a
     * changes, then realloc() copies the data from the old location to
     * the new location. */
    list->a = realloc(list->a, (list->n + 1) * sizeof list->a[0]);

    /* Now store the value in the (empty) new location at end of the list. */
    list->a[list->n++] = val;
}

/* Return the item at index idx in the list. */
static int listGet(const List_t *list, int idx)
{
    /* Ensure the index is within bounds. */
    assert(idx < list->n);

    return list->a[idx];
}

/* Return the size of the list. */
static int listSize(const List_t *list)
{
    return list->n;
}

int main(int argc, char *argv[])
{
    List_t list;
    int    i, size;

    listInit(&list);

    /* Add the values on the command line to the list.
     * Ignore argv[0] which is the program name. */
    for (argc--, argv++; argc--; argv++)
    {
        listAddEnd(&list, atoi(*argv));
    }

    /* Output the contents of the list. */
    for (size = listSize(&list), i = 0; i < size; i++)
    {
        printf("%2d: %8d\n", i, listGet(&list, i));
    }

    return 0;
}

$ gcc -Wall list.c
$ a.out 1 5 7 10 127
 0:        1
 1:        5
 2:        7
 3:       10
 4:      127


Reply via email to