我一直在研究哈希表。我不断收到分段错误。我一直在尝试调试它,但它总是指出存在addOrder
分段错误。
我哪里错了?还有什么其他方法可以实现我的代码来检查任何极端情况?
struct order
{
int id;
char side;
int quantity;
double price;
};
struct onode
{
struct order* data;
struct onode* next;
struct onode* prev;
};
/*
* Create a new instance of struct hashStorage and return it. It sets the size of the
* table to be of length "size" which will be the number of the entries in the hash. It takes also an
* argument to specify the format of the order printed to an output stream. If myHash parameter
* is NULL then this means that the hash should be a linked list. When myHash is NULL the size
* parameter should be ignored.
*/
struct hashStorage* createHash(int size, int (*myHash)(int),void(*printOrder)(struct order *, FILE *))
{
struct hashStorage* hashList = (struct hashStorage*) malloc(sizeof(struct hashStorage));
if(myHash == NULL)
{
hashList->size = 1;
hashList->table = (struct onode**) calloc(1, sizeof(struct onode*));
}
if(myHash != NULL)
{
hashList->table = (struct onode**) calloc(size, sizeof(struct onode*));
hashList->size = size;
}
hashList->funcHash = myHash;
hashList->printItem = printOrder;
return hashList;
}
/*
* Add an order to the hash structure. Remember that you should copy the data before
* adding it to the hash as data can be modified (hint: look at newNode in list).
* It returns the new onode.
*/
struct onode* addOrder(struct hashStorage* hash, struct order* data)
{
int addIndex;
struct onode* dataList = newNode(data);
addIndex = hash -> funcHash(getOrderId(data));
pushNode(&(hash->table[addIndex]), dataList);
return dataList;
}