I am trying to wrap my head around C right now (mostly how pointers operate). I am trying to write this function described below:
/* EnterName enter a Name into a symbol table. Returns a
boolean indicating whether an entry for Name was
already listed in the table. Passes back an argument
containing an entry reference for the name.
Anyway, here is the code I have written and I am not sure how to test it at the moment. Wondering if someone could look over it and let me know if I am doing this right.
Thanks in advance.
Code::
bool EnterName(struct SymTab *ATable,
const char *Name,
struct SymEntry * *AnEntry)
{
char name = *Name;
unsigned hashval = hash (&name);
struct SymEntry *ptr;
ptr = ATable->Contents[hashval];
while(ptr != NULL)
{
if(strcmp(ptr->Name, &name))
{
AnEntry = &ptr;
return true;
}
}
ptr = malloc(sizeof(struct SymEntry));
ptr->Name = &name;
AnEntry = &ptr;
return false;
}
Does it run and produce the results you expect?
There’s no replacement for compiling code, running it with test data, comparing results to expected values, debugging, etc, when learning a new language. Showing untested code to others and asking if it’s OK isn’t the right approach.
Even the first two lines of the function don’t make sense:
You’ve just taken the first character of
Nameinto thenamevariable, and then try to hash its address.Now, the loop:
Doesn’t make sense either, since you’re not advancing
ptranywhere – it’s an infinite loop.That said, there seems to be a step in the right direction in your code. You just have to get your types straight and fix all the rough corners. I suggest starting with small pieces – see that they compile and run, then proceed assembling into larger pieces.