我有以下代码会产生编译错误。它用于用C ++编写的STM32微控制器的命令解析器。基本上,我有一个CMD_DEF_ST
带有字符串的结构和一个处理该字符串的函数指针。我CMD_DEF_ST
在结构中添加了另一个指向另一个数组的指针,以便能够处理命令参数。不幸的是,我无法正确进行初始化。我不想在运行时初始化它,因为所有这些都必须放入const FLASH内存中。
#include <stdio.h>
// **************************
// define command structure
// **************************
// struct forward declaration
typedef struct cmd_def_st CMD_DEF_ST;
// typedef for command handler function
typedef void (*CMD_FUNC_HANDLER)(const CMD_DEF_ST* cmddef);
struct cmd_def_st
{
const char* cmdstr; // command string
const CMD_FUNC_HANDLER func; // pointer to handler
const CMD_DEF_ST* params; // pointer to sub parameters
};
// **************************
// declare some commands
// **************************
const CMD_DEF_ST cmd = {"swrst" , [] (const CMD_DEF_ST* cmd) { printf("swrst\n"); },
NULL};
// **************************
// produces:
// error: braces around scalar initializer for type 'const CMD_DEF_ST*
// {aka const cmd_def_st*}'
// **************************
const CMD_DEF_ST cmd2 = { "echo" , [] (const CMD_DEF_ST* cmd) { printf("Error\n"); },
{
{"on" , [] (const CMD_DEF_ST* cmd) { printf("Echo on\n"); }, NULL },
{"off" , [] (const CMD_DEF_ST* cmd) { printf("Echo off\n"); }, NULL },
NULL
}
};
int main()
{
cmd.func(&cmd); // prints "swrst"
return 0;
}
我在这里看到了gcc警告:在标量初始化程序周围加括号,并在此处初始化指向struct的指针数组。它给了我一些尝试的想法,但是我无法弄清楚如何使其适用于我自己的代码。
我尝试将结构定义更改为:
struct cmd_def_st
{
const char* cmdstr; // command string
const CMD_FUNC_HANDLER func; // pointer to handler
const CMD_DEF_ST** params; // pointer to sub parameters
};
与
// **************************
// produces:
// error: taking address of temporary [-fpermissive]|
// error: taking address of temporary [-fpermissive]|
// error: taking address of temporary array|
// **************************
const CMD_DEF_ST cmd2 = { "echo" , [] (const CMD_DEF_ST* cmd) { printf("Error\n"); },
(const CMD_DEF_ST* []){
&(const CMD_DEF_ST){"on" , [] (const CMD_DEF_ST* cmd) { printf("Echo on\n"); }, NULL },
&(const CMD_DEF_ST){"off" , [] (const CMD_DEF_ST* cmd) { printf("Echo off\n"); }, NULL },
NULL
}
};
但是我仍然遇到编译错误。
有人可以告诉我初始化的正确方法是什么cmd2
,还是有人知道这样做的好方法?
如果在使用的cmd_def_st结构中,您const CMD_DEF_ST* params;
尝试使用结构数组初始化标量类型(指针)。因此,这里您实际上需要一个CMD_DEF_ST类型的地址(就像超级答案中建议的那样)。
在第二种情况下,您试图获取一个右值的地址,这是一个临时对象,该临时对象将在当前语句之后不复存在,因此您将收到错误消息。
如果您对两步初始化不满意,我可能建议同时为cmds和subcmds构造结构,以为params数组中的类型提供完整性cmd_def_st
:
struct subcmd_def_st
{
const char* cmdstr; // command string
const CMD_FUNC_HANDLER func; // pointer to handler
// const SUBCMD_DEF_ST params; // assuming no sub-subcmds
};
struct cmd_def_st
{
const char* cmdstr; // command string
const CMD_FUNC_HANDLER func; // pointer to handler
const subcmd_def_st params[]; // pointer to sub parameters
};
const CMD_DEF_ST cmd2 =
{
"echo" ,
[] (const CMD_DEF_ST* cmd) { printf("Error\n"); },
{
{ "on" , [] (const CMD_DEF_ST* cmd) { printf("Echo on\n"); } },
{ "off" , [] (const CMD_DEF_ST* cmd) { printf("Echo off\n"); } },
{ NULL }
}
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句