我是 C 编程语言的初学者,我想编写一个散列程序。我可以用指定数量的typedef ... Name
元素(在数组中)编写这个程序,但是当我使用动态分配时,会出现“无效的初始化程序”错误。
typedef char Name[30];
Name hashTable[MAX];
int hash(Name name){
int long sum = 0;
int len=strlen(name);
int i = 0;
for (; i<len;i++)
sum += name[i];
sum = sum % MAX;
printf("\nhash of [%s] = %ld\n",name,sum);
return sum;
}
void main(){
int i,j;
for(i=0;i<MAX;i++)
strcpy(hashTable[i],"");
int pos, x, cont=1;
printf("number of names: ");
scanf("%d",&x);
while (x>=cont){
Name name = malloc(sizeof(Name)); // why this line have the error of "invalid initializer"?
printf("\ntype the %dº name: ",cont);
scanf("%s",name);
pos=hash(name);
strcpy(hashTable[pos],name);
cont++;
}