前提・実現したいこと
3 桁の数値 x に対して,ハッシュ関数の値 h(x) をハッシュテーブルのインデックスとして用い,これを先頭とする線形リストに連結するプログラムを実装しようとしています。
実装中に以下の実行結果が出力されました。
##実行結果
Linear-List:
No. Pointer Linked to
-1 0x7ffc77076d90 0
-1 0x7ffc77076d90 0
-1 0x7ffc77076d90 0
-1 0x7ffc77076d90 0
-1 0x7ffc77076d90 0
-1 0x7ffc77076d90 0
-1 0x7ffc77076d90 0
-1 0x7ffc77076d90 0
-1 0x7ffc77076d90 0
-1 0x7ffc77076d90 0
*** stack smashing detected ***: <unknown> terminated
中止 (コアダンプ)
該当のソースコード
C++言語
ソースコード
#include<iostream>
#include<string>
#include<ctime>
using namespace std;
struct CELL{
int data;
CELL *next;
};
void add_list( CELL * ,int);
void show_hash_table( CELL ** );
int Hash(int);
int main( void ){
const int Hash_NUM = 20;
const int num=10;
int data[num]={99,88,77,66,55,44,33,22,11,0};
int hash[num];
CELL *Hash_Table[num];
for(int i=0;i<Hash_NUM;i++){
Hash_Table[i]=new CELL;
Hash_Table[i]->data=-1;
Hash_Table[i]->next=NULL;
}
for(int i=0;i<num;i++){
hash[i]=Hash(data[i]);
if(hash[i]==i){
add_list(Hash_Table[i],data[i]);
}
}
show_hash_table(Hash_Table->next);
return 0;
}
int Hash(int data){
int hash;
hash=data%20;
return hash;
}
void add_list(CELL *hashtable,int data){
CELL *newcell = new CELL;
while( hashtable->next != NULL ){
hashtable = hashtable->next;
}
newcell->next = hashtable->next;
hashtable->next = newcell;
newcell->data = data;
}
void show_hash_table( CELL **p ){
cout << "-----------------------------" << endl;
cout << " Linear-List: " << endl;
cout << " No. Pointer Linked to" << endl;
cout << "-----------------------------" << endl;
for(int i=0;i<10;i++){
while( p[i] != NULL ){
cout << " " << p[i]->data << " " << p << " " << p[i]->next << endl;
p[i] = p[i]->next; /* 次のセルにポインタを移動 */
}
}
cout << "-----------------------------" << endl;
}
関数add_listは新しい入力に対してハッシュテーブルに線形リストを連結させる関数
関数Hashはハッシュ値を求める関数
関数show_hash_tableはハッシュテーブルを連結順に出力させる関数
です。