Afficher un message
Vieux 18/10/2007, 14h03   #2
Ben Bacarisse
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: Initialize the HashTable

westlaker <westlaker@126.com> writes:

> The declaration is:
> 1
> 2 struct ListNode;
> 3 typedef struct ListNode *Position;
> 4 typedef Position List;
> 5 struct HashTbl;
> 6 typedef struct HashTbl *HashTable;
> 7
> 8 struct ListNode{
> 9 char name[4];
> 10 int GroupID;
> 11 Position Next;


I think lists are much clearer if you make the link explicit:
struct ListNode *Next;
Now everyone can see at a glance that this is a linked list.

> 12 };
> 13
> 14 struct HashTbl
> 15 {
> 16 int TableSize;
> 17 List *TheLists;
> 18 };
> 19
> 20 //The Initialization Function:
> 21
> 22 struct HashTbl *InitializeTable(int TableSize)


An unsigned type is often better for a size (in particular size_t).
If you use an int, you should check that the value it is not negative.

> 23 {
> 24 HashTable H;
> 25 int i;
> 26
> 27 H->TableSize=TableSize+3;
> 28
> 29 /* Allocate Table */
> 30 H=(HashTable)malloc(sizeof(struct HashTbl));


Too late. You have used H on line 27. The cast is not needed (and
may be a problem). The c.l.c idiom is:

H = malloc(sizeof *H);

(I had to check that HashTable is indeed a synonym for a pointer to a
struct HashTbl.)

> 31 if(H == NULL)
> 32 fprintf(stderr,"Out of space!!!");


Having found H to be NULL, it is not safe to just carry on!

> 33
> 34 /* Allocate array of lists */
> 35 H->TheLists=(List *)malloc(sizeof(List)*H->TableSize);
> 36 if(H->TheLists == NULL)
> 37 fprintf(stderr,"Out of space!!!");


Ditto.

> 38
> 39 for(i = 0; i < H->TableSize; i++)
> 40 H->TheLists[i]=NULL;
> 41 return H;
> 42 }


--
Ben.
  Réponse avec citation
 
Page generated in 0,05206 seconds with 9 queries