Home > Back-end >  C: Indexed Array for Hashtable which itself consists of N “struct nodes”: Struggling to access singl
C: Indexed Array for Hashtable which itself consists of N “struct nodes”: Struggling to access singl

Time:10-08

The problem is about an indexed array for a hashtable, which itself consists of a number N of “struct nodes”, see code below. Each field of the array is the head of a linked list which is to be filled in later.

I am trying to access a field (as defined below in “struct node”) of a specific indexed element of this array.

LENGTH and N are previously defined constant integers, that is they are 45 and 5, respectively.

  typedef struct node
  {
      char word[LENGTH   1];
      struct node *next;
  }
  node;

  // Hash table
  node *table[N];


     // initialize hashtable
    for (int i = 0; i < N; i  )
    {
        (table[i]->next) = NULL;
    }


The code (which is obviously part of a larger program) compiles correctly but I receive a “segmentation fault” on debug here

(table[i]->next) = NULL

My guess is that it might be a syntax problem because I can't really see any other possible issue here.

Can somebody help? Thanks in advance!

CodePudding user response:

The declaration

node* table[N];

is not declaring an array of node structs, it is declaring an array of pointers to node structs. As I don't see any place where you initialize the array itself, I assume you are not doing it.

The correct way would be (modernizing your code a little):

struct node
{
  char word[LENGTH   1];
  struct node *next;
};

// Hash table
std::array<node,N> table;


// initialize hashtable
for ( node& n: table )
{
    n.next = nullptr;
}

CodePudding user response:

The answer from Jellyboy pointed me in the right direction: I need to declare an "array of node structs", and not an "array of pointers to node structs".

So the solution is simply:

node table[N];      // (instead of:   node* table[N];

And then I am also able to initialize my hashtable, i.e. this array ("table") of N "struct nodes", and these will later serve as start points for linked lists.

I was led in the wrong direction because in the distributed "raw code" that I received in this online course, there was this statement (which included the *), and I didn't think I would have to change it.

And, as I said, I am really very new to coding, so bear with me.

  • Related