Hi everyone,
I am using the HashMap library and I am getting unknown output. The following is my setup. I have verified the hash map that I have created using the debug function and the following are the results of the serial prints. temp: 1010, lookUpvar: 1010, strcmp prints 0, but LookUpResult prints "' ? ? ?" (inverted question marks) rather than printing the value in the hash map. Anyone knows why is this happening?
lookup_result = Map.getValueOf(&lookup_var[0]);
[\code]
Check your operator precedence. First, you take the subscript (which I'm assuming returns a char, but you didn't define that in your sketch) and then you take the address of that. Probably not what you want.
just just the variable as-is
[code]
lookup_result = Map.getValueOf(lookup_var);
[\code]
Hey sorry, I just added the declarations. Really sorry, it is an excerpt from a really long code. That was why I missed it. And I tried that too. It did the same thing; printed the same random output. Also, adding one more point, when hardcoding the variable as being char* temp_1 = "1010", It returned the appropriate output when being called as Map.getValueOf(temp_1). Anyone knows why?
char lookup_var[4]; is too small to hold "1010" - you forgot the C-string null termination character.
Looking at the library code here, it is not a piece of well polished software. There are functions that are supposed to return values, but don't or don't always.
You are trying to use a low level C-string when a higher level construct is required. Basically, you cannot use a simple char* as a hash key because when you use the equality operator (==) you are comparing pointers, not the content of the C-string. That causes the getValueOf() function to fail.
Function edited with your template types:
char* getValueOf( char* key ){
for (byte i=0; i<size; i++){
if (hashMap[i].getHash()==key){ // ERROR: The strings may be equal, but the pointer values are compared here!
return hashMap[i].getValue(); // So we sometimes don't return a value here.
}
}
// And now a missing return statement means undefined results.
}
I guess the HashMap may be usable with a String class key, but use of String is frowned upon here.
Hi there, I have tried increasing the size to 5 to account for the null-termination character. The code still displays the same output as above (gibberish). Also, somehow I am not allowed to use type string when declaring the HashMap. The IDE gave me an error saying, error compiling for Arduino/Genuino Uno.
Hi, thank you everyone! I ended up solving the problem by changing the code in the HashMap library to use strcmp instead of the == sign. Thank you so much for your time!