0

im new to C and trying to understand some fundamental stuff. I'm trying to create a struct which holds an array that consists of linked lists. Something around this.

--------------------------------
|    A    |     B    |    C    |
--------------------------------
      |         |          | 
      V         V          V
   -------    -------    -------
   |  a  |    |  b  |    |  c  |
   -------    -------    -------
      |
      V
   --------
   |  a1  |
   --------

Meaning ill have an array which holds the head(A, B and C) of each linked list and each head will hold a pointer to the next node.

I have a struct Object

typedef struct Object {
    void* data;
    struct Object* next;
    struct Object* head;
}Object;

And a table which holds some more info

typedef struct Table {
    Object** arr;
    //More info...//
}Table;

I have a function which should create a table with the array.

Table* createTable(){

    Table* table = (Table*)malloc(sizeof(struct Table*));

    Object **array = (Object**)malloc(3*sizeof(struct Object*));

    for(int j = 0; j < size; j++){
        array[j] = malloc(sizeof(struct Object));
    }
table->arr = array;
return table;

}

But all my memory isn't working as i hoped for, i keep getting an array with just one node. I guess im still missing some basic stuff.

Thanks

arcone
  • 1
  • `malloc(sizeof(struct Table*)`-> `malloc(sizeof(struct Table)` – Stephan Lechner Feb 01 '19 at 23:27
  • ... and what is `size` in `for(int j = 0; j < size; j++)`? – Stephan Lechner Feb 01 '19 at 23:28
  • See [Do I cast the result of malloc?](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). Also, what you are doing is not much different that setting up a hash-table. You may want to look at how the "buckets" (array) hold the head for the "chained" lists that are implemented when collisions occur. `Object **array = malloc (3 * sizeof *array);` is sufficient. – David C. Rankin Feb 01 '19 at 23:32

1 Answers1

1

There is a mistake in Table* table = (Table*)malloc(sizeof(struct Table*)), which should be Table* table = malloc(sizeof(struct Table)).

But the rest of your code is written such that it will create an array of size 3 of pointers to Object, and it will initialize this array by letting each element of it point to one Object that you create (I suppose that your size-variable is initialized somewhere else to 3, otherwise you now know where to search). So it is clear that you get just one element at each position of your array, you simply do not create more...

Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58