This is the function that checks the name of the function entered by the user into the interpreter/parser I am making, compares it with the array of functions, and executes the corresponding C++ function. It works fine as long as the user enters a correct function name, but the interpreter ends with some unexplained runtime error if there is no function of the name the user entered, even though I programmed it to print “Undefined Function” and then carry on the parse loop:
void parser::eval_cmd(std::string& exp, pro::command fset[])
{
expr = exp;
exp_ptr = (char*) expr.c_str();
bool found = false;
for (int i = 0; i < (int)sizeof(fset); i++)
{
if (fset[i].check(expr))
{
found = true;
exp_ptr = (char*)expr.c_str() + (fset[i].name.size() - 1);
if (fset[i].cmd)
fset[i].cmd(eval_args());
break;
}
}
if (!found) err::show(err::UNDEFINED);
}
What exactly am I doing wrong?
What you are doing wrong is
(int)sizeof(fset). That gives you the size of a pointer, in bytes, not the number of elements in the passed-infsetarray.You need some other way of determining how many elements are in the array, perhaps by passing in another arg, by using an
std::container instead of an array, or by NULL-terminating the array.For example, changing your function definition slightly:
The remainder of the code is unchanged.
EDIT: My best advice is to use
std::map<string, pro::command>and allowmapto manage the lookup algorithm, orstd::vector<pro::comand>and use the above algorithm unchanged. You can measure the memory performance, but I expect that the only overhead ofvectorover array is the overhead of anewed array over a static array.If you do reach the conclusion not to use standard containers, here is my 2nd-best advice:
Presumably the caller knows (or can determine) the number of elements in the fset array. (See Can this macro be converted to a function? for help with that.)