I have this (strange) problem:
I'm implementing a sort of hash table and I have to insert some predefined elements into it and here is the problem:
if I push these new entries with a function defined in a source file, the find function doesn't work, but if I push them with the same function but defined in the main function file it all works.
Here is some code:
HEADER
//SymbolTable.h
typedef struct element
{
const char* name;
int address;
struct element* prev;
} element_t;
typedef element_t* elemPoint;
//definition of functions
SOURCE
//SymbolTable.c
//include libraries and header file
static elemPoint last;
static elemPoint iterator;
void init()
{
last = NULL;
pushSymbol("SP",0);
pushSymbol("LCL",1);
pushSymbol("ARG",2);
pushSymbol("THIS",3);
pushSymbol("THAT",4);
}
void pushSymbol(const char* nameVar, int addressVar)
{
elemPoint pushed = malloc(sizeof(element_t));
pushed-> prev = last;
pushed-> name = nameVar;
pushed-> address = addressVar;
last = pushed;
}
int findName(const char* nameVar)
{
iterator = last;
while(iterator!=NULL)
{
if(iterator->name == nameVar)
{
return 1;
}
else
{
iterator = iterator->prev;
}
}
return 0;
}
MAIN
//main.c
//include libraries and header
int main()
{
init();
if(findName("LCL")) puts("true");
else puts("false");
}
The output of this code is false
, but if I put the entire init()
function in the main module the output is true
.
So I thought that maybe the problem was with the iterator
variable.
And there's the strange thing, while debugging I put a printf
of iterator->name
right after the while
in the findName
function, and the output was correct (all the elements name were printed on the std output).
So now I'm assuming that the problem is in the comparison iterator->name == nameVar
, but I can't understand why.