
Can function returning pointer return negative integers?
I'm implementing a hash table and when the client puts a value/item into
the table, there are two possibilities. Either the value/item is already in
the table or it is not. If it is not, memory needs to be allocated to make
another link in one of the chains of the table. This leads to two possible
outcomes, either the memory can be allocated or it can not. It's a generic
hash table meaning the data is stored into it as void pointers and each item
of data has a specific key that indexes it into the hash table. Here's what
I'd like to do. If the client tries to put data into the table and data is
already attached to the specific key for that data, to return the old data
(which will be a pointer) to the client and put the new data in the table.
If the key is not already in the table, just store the pointer in the table.
But either the memory for the new "bucket" can be allocated or it can't.
So here's my problem. I'd like to return any existing data to the client which
would be a positive return value because it's a pointer. If the key did not
already exist and the malloc succeeded, I'd like to return NULL. And if the
malloc fails I'd like to return -1. But the compiler is complaining about me
returning -1 because the function is declared to return pointers and pointers
can't be negative. For now, I've typecasted the return statement that's
returning the -1 and the compiler is not complaining. My concern is something
odd happening like returning -1 and the compiler wrapping it to a positive
number because pointers can't be negative (Or memory addresses can't be
negative at least). Sorry if that's lengthy but I want to give you guys
enough info to help me understand yet another aspect of the C programming
language. 8)
Robert