I’m trying to build a serial command interpreter, so I want to store my commands in an array. I want each command to have a name and a function pointer so that I can compare the command name to what I typed into and then call the function. I’m not that good with C, so please help! Here is what I have so far.
The command array will be an array of structs. Each struct will have a string and a function pointer. There are errors here, but I don’t know how to fix them. These are done before main.
typedef struct cmdStruct {
char cmd[16];
void (*cmdFuncPtr)(void);
}CmdStruct;
void (*ledFuncPtr)(void);
void (*cmd2FuncPtr)(void);
// assign pointers to functions
ledFuncPtr = &LedFunction;
cmd2FuncPtr = &Cmd2Function;
//build array of structs
CmdStruct cmdStructArray[] = cmdStructArray = { {"led", ledFuncPtr },
{"cmd2", cmd2FuncPtr }, };
Later on, I will go through the struct array to compare it to the received command.
// go through the struct array to do string comparison on each struct's string member
for (int i = 0; i < sizeof(cmdStructArray); i++) {
// string comparison of received command and string of struct
if(strcmp(cmdStructArray[i].cmd, receivedCmd)==0) {
// dereference function pointer
(*cmdStructArray[i].cmdFuncPtr)(void);
}
}
What parts am I doing wrong, and how do I fix them?
As it has already been noted, your cycle makes wrong number of iterations.
sizeof arraydoes give you the number of elements in the array, but rather the number of bytes in the array. You have to calculatesizeof array / sizeof *arrayto get the number of elements.Also, your function call syntax is invalid
The above will not compile. You cannot specify
voidas an argument in function call.(void)syntax can only be used in function declarations. If the function accepts no parameters, the call should look asAlso, this will not compile as well
Why are you mentioning
cmdStructArrayin this declaration twice?Some additional, essentially cosmetic remarks:
Firstly, since your commands are probably going to be string literals known at compile time, you can declare the first member of your struct as a
const char *pointer instead of char arrayThe initialization syntax does not change. This will relieve you of the need to worry about the size of the array (
16that you currently have there).Secondly, it is not clear why you had to declare intermediate pointers to functions
ledFuncPtrandcmd2FuncPtrinstead of initializing your array directly. What was the purpose of thiswhen you could simply do this
(without introducing
ledFuncPtrandcmd2FuncPtrat all)?Thirdly, you don’t have to use
*and&operators with function pointers. This will work tooand
Anyway, this is a purely cosmetic issue, a matter of personal preference.