2

I get this message when trying to insert an object to a table (struct) that holds an array of a struct type ObjectLink. The structs:

typedef struct ObjectLink {
    void *key;
    struct Object *next;
} ObjectLink;

typedef struct Object {
    void *key;
    ObjectLink *top;
} Object;

typedef struct Table{
    ObjectLink *linkedObjects;
    int size, originalSize;
    HashFcn hfun;
    PrintFcn pfun;
    ComparisonFcn fcomp;
} Table;

The code that is failing (on all assignments & if statement):

Boolean InsertObject(TableP table, ObjectP object)
{

    int i = table->hfun(object, table->size);
    if (table->linkedObjects[i]->key == NULL)
    {
        table->linkedObjects[i]->key = object;
    } else
    {
        table->linkedObjects[i]->next->key = object;
    }

    return TRUE;
}

I've searched in previous questions but that didn't help. What is wrong here?

Community
  • 1
  • 1
Tom
  • 9,275
  • 25
  • 89
  • 147

2 Answers2

4

Since linkedObjects is a pointer, linkedObjects[i] is the object itself. The -> operator works only on pointers; when you have a struct, you need to use the regular dot operator . for field access:

table->linkedObjects[i].key = object;
//                     ^--- Here
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • So why isn't table which is a struct by itself and not a pointer isn't called like: table.linkedObjects[i].key – Tom Dec 24 '12 at 14:30
  • 1
    @Tom `table` is of type `TableP`, which is not shown in the definitions; however, `P` probably stands for `Pointer`. – Sergey Kalinichenko Dec 24 '12 at 14:34
3

The array subscripting operator [] is defined as: E1[E2] == *((E1)+(E2)). With ->, you are trying to dereference a pointer which doesn't exist (because you've already dereferenced your pointer with the operator []). So the right solution is:

table->linkedObjects[i].next->key = object;

Instead of:

table->linkedObjects[i]->next->key = object;

linkedObjects[i] is of type ObjectLink, no need to dereference it.

md5
  • 23,373
  • 3
  • 44
  • 93