3

I'm a beginner in the C Programming language and I wanted to write a hashing program. I can write this program with a specified number of typedef ... Name elemenst (in an array) but, when I use dynamic allocation, an "invalid initializer" error appears.

    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++;
    }
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
Otavio Mota
  • 31
  • 1
  • 1
  • 5

2 Answers2

3

I know this answer is late, but I made a similar stupid mistake. variable Name name should be a pointer. i.e Name * name

null
  • 169
  • 1
  • 13
  • It should probably be `char *name` . The program would need other changes in order to use `Name *name` as then the other uses of `name` in function calls become incorrect – M.M Feb 26 '21 at 01:36
  • of course, this is assuming that the simple `Name name;` is undesirable for some reason – M.M Feb 26 '21 at 01:36
0

Your declaration of name makes it statically (not dynamically) allocated. Therefore you do not need to use malloc() to allocate space.

sigpipe
  • 76
  • 3