ligerdave said:
i have the following code:
/* Created by Anjuta version 1.2.2 */
/* This file will not be overwritten */
#include <stdio.h>
#define LEN sizeof(struct hash_table)
struct hash_table{
int value;
char *key;
struct hash_table *next;
}
struct hash_table* allocate_hash_table(int size){
struct hash_table* head;
head = (struct hash_table*) calloc(size, LEN);
return head;
}
int main()
{
return (0);
}
and i always get error which says: two or more data types in
declaration of 'allocate_hash_table'
Others have pointed out the missing semicolon. I have some other
comments.
The macro LEN isn't really useful. You only use it once, and it would
be clearer to use sizeof explicitly.
You should never cast the result of calloc() or malloc(). It can mask
the error of failing to add a "#include <stdlib.h>" -- which you also
need. (You also don't need the "#include <stdio.h>", since the
program doesn't do any I/O, but presumably it's not a complete
program.)
The difference between malloc() and calloc() (other than a different
way of specifying the size) is that calloc() initializes the allocated
space to all-bits-zero. Since the structure contains pointers,
setting it to all-bits-zero isn't necessarily meaningful; it makes
more sense to initialize them to null pointers (and a null pointer is
*not* necessarily all-bits-zero).
A simple malloc() will allocate the space without initializing it; you
can then initialize the structures manually if necesary.
And a couple of minor points: "int main()" is allowed, but
"int main(void)" is preferred, and you don't need parentheses on the
return statement.
Here's a modified version of your program:
struct hash_table {
int value;
char *key;
struct hash_table *next;
};
struct hash_table *allocate_hash_table(int size)
{
struct hash_table *head;
head = malloc(size * sizeof *head);
return head;
}
int main(void)
{
return 0;
}
You should always check whether malloc() succeeded. In this case, it
may be acceptable for allocate_hash_table() to return the result of
malloc() without checking it, and let the caller check whether
allocate_hash_table() returned a null pointer. But if
allocate_hash_table() is going to initialize the allocated memory, it
*must* check the result of malloc() before doing so.
What to do if malloc() fails is another matter. You may sometimes be
able to recover somehow, but the simplest thing to do is to abort the
program with an error message -- which is better than continuing
blindly with an invalid pointer.