Reputation: 7
Function is waiting for a pointer but I want to return an integer in the function lookup (i can't modify the return type of the function), what can i do to solve this problem ?
int hashtable_insert(HashTable ** ptable, void *data, void (*delete) (void *))
{
if(hashtable_lookup(*ptable, data) != -1){
return -1;
}
data = malloc(sizeof(size_t));
list_append((*ptable)->list, data, (*ptable)->size);
_hashtable_resize(ptable);
return 0;
}
warning: comparison between pointer and integer if(hashtable_lookup(*ptable, data) != -1){
void * hashtable_lookup(HashTable * table, void *data)
{
for(int i = 0; i < (table)->length; i++){
if((table)->list[i] == data){
return data;
}
}
return -1;
}
warning: return makes pointer from integer without a cast [-Wint-conversion] return -1;
Upvotes: 0
Views: 65
Reputation: 180093
Function is waiting for a pointer but I want to return an integer in the function lookup (i can't modify the return type of the function), what can i do to solve this problem ?
If the function returns void *
and you cannot change that, then returning an integer simply is not an option. You could return an integer converted to a pointer (and compare the return value against a similar value), but unless your hash table supports null values, a null pointer would make a better failure code:
void * hashtable_lookup(HashTable * table, void *data) {
// look up data ...
// lookup failed
return NULL;
}
// ...
if (hashtable_lookup(*ptable, data) != NULL) {
// data is already present in the hash table
return -1;
}
But if a null pointer would be valid data for the table, then
void * hashtable_lookup(HashTable * table, void *data) {
// look up data ...
// lookup failed
return (void *) -1;
}
// ...
if (hashtable_lookup(*ptable, data) != (void *) -1) {
// data is already present in the hash table
return -1;
}
Upvotes: 2
Reputation: 69
First warning is because you are comparing a void*
to an int
. The second one is because you're returning an int
instead of a pointer.
You could add casts here and there to remove the warnings (if(hashtable_lookup(*ptable, data) != (void*)(-1)){
and return (void*)(-1);
, but it would be harder to read and more error-prone since you usually check pointers to not be NULL, but not to be different than "-1".
Typically, you would return a NULL pointer to indicate that the function failed. Also, you might have if(hashtable_lookup(*ptable, data) != -1){
wrong since it looks like when hasthable_lookup() returns -1 it failed.
I think this is what you are looking for.
int hashtable_insert(HashTable ** ptable, void *data, void (*delete) (void *))
{
if(hashtable_lookup(*ptable, data) == NULL){
return -1;
}
data = malloc(sizeof(size_t));
list_append((*ptable)->list, data, (*ptable)->size);
_hashtable_resize(ptable);
return 0;
}
void * hashtable_lookup(HashTable * table, void *data)
{
for(int i = 0; i < (table)->length; i++){
if((table)->list[i] == data){
return data;
}
}
return NULL;
}
Upvotes: 1