I am developing a program that will search for the desired element using a hash table. The hash table is organized by creating an array consisting of LOS (Linear singly-linked lists) Structure declaration:

struct LOS { int inf; LOS* next; }; 

The code of the program itself is quite simple; in the sourcelen variable, I write the length of the numeric array, which will contain the original data, in x, I will write the array elements (if the array length is less than 5), if more, then the array will be filled with a pseudo-random number sensor. Next, using the Maximum function, I will find the largest value of the element in the hasharray array. After that, I calculate the size of the array consisting of LOS. and using hashFunc, I will fill in an array consisting of LOS.

 int main() { setlocale(LC_ALL, "RUS"); int sourcelen = 0;; int x = 0; int m; cout << "Введите размер массива = "; sourcelen = control(sourcelen); int* hasharray = new int[sourcelen]; if (sourcelen > 5) { for (int i = 0; i < sourcelen; i++) { srand(time(0)); hasharray[i] = rand(); } } else { cout << "Введите элементы массива" << endl; for (int i = 0; i < sourcelen; i++) { x = control(x); hasharray[i] = x; } } m = Maximum(hasharray, sourcelen) /2; int k = 0; k = (int)(sourcelen / m); if (k < 9) k == 9; LOS** list = new LOS*[k]; for (int i = 0; i < k; i++) { list[i]->next = NULL; } hashFunc(list, hasharray, sourcelen, m); cout << "Вывод" << endl; for (int i = 0; i < k; i++) { while (list[i]->next) { cout << list[i]->inf << " "; list[i] = list[i]->next; } } 

The problem occurs in the hashFunc function

 void hashFunc(LOS ** list, int *i, int size, int m) { for (int j = 0; j < size; j++) { int t = (i[j] % m); list[t]->inf = i[j]; list[t] = list[t]->next; list[t]->next = NULL; } } 

Throws an exception on the line.

 list[t]->inf = i[j]; 

Well, can I understand what I'm doing wrong? enter image description here

  • k == 9 - probably there should be an assignment? - acade
  • yes, thanks, just start throwing an exception now on the string list [i] -> next = NULL; - i_burykin
  • This happens when the preceding list[i]->next operation is NULL . Thus, a call is made at the null pointer. As an option, make a check before the list[i]->next = NULL . Although the presence of this assignment is generally in doubt. - acade
  • understood, thanks, corrected, but there was a question about the hashFunc function, it still swears at the value assignment string. list [t] -> inf = i [j]; why it happens? and how to fix it? - i_burykin
  • In the main function, you incorrectly allocated memory for the list . LOS** list = new LOS*[k] - means the allocation of memory for an array of pointers , not LOS objects. You need to allocate the memory list[i] = new LOS() for each object in the cycle following each instruction. Or initially create a list as an array of LOS objects, i.e. LOS* list = new LOS[k] - acade

0