2013-03-29 61 views
1

我是C編程語言的初學者。我想寫一個哈希程序。我可以使用有限數量的typedef名稱來執行此程序,但是當我使用動態分配時,會出現無效的初始化程序錯誤。無效初始化程序 - C

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++; 
} 

回答

0

你的名字聲明使得靜態(非動態)分配。因此你不需要使用malloc()來分配空間。

0

我知道這個答案很晚,但我犯了一個類似的愚蠢的錯誤。變量Name name應該是一個指針。即Name * name