c - 指向函数指针的 C 指针数组将程序中断超过一定长度
问题描述
嗨,我试图从微控制器接收的字符串中调用函数。为此,微控制器 find 接收并将其与外围设备名称列表中的名称进行比较。它使用索引获取指向该外围设备可用的函数名称列表的指针,然后将函数名称与该列表进行比较以获得函数索引。然后使用这两个索引来调用函数。
系统在 2 个外设上工作正常,但添加第三个外设会导致程序停止运行,有时会发出警告堆栈指针超出范围,有时会在程序暂停时不显示任何位置。将第三个外设添加到 peripheral_fnct_pntr_pntr 列表会导致这种情况发生,它可以在 2 个外设的所有组合中正常工作,并且注释该行也可以正常工作。
我为函数指针制作了自定义类型,如下所示:
typedef void (*fp)(int); //Declares a type of a void function that accepts an int
typedef char (*p)[6][20]; //pointer to array
函数和指针列表的创建如下所示:
char peripheral_names[6][20] = {"rgb","button"}; //[no of strs][size of str]
char rgb_fnct_names[6][20] = {"rgb_brightness","red_brightness","green_brightness","blue_brightness","rgb_onTime","rgb_breath"};
char led1_fnct_names[6][20] = {"led1_brightness","led1_onTime","led1_breath"};
char led2_fnct_names[6][20] = {"led2_brightness","led2_onTime","led2_breath"};
//store pointers linking name to functiion index to function
//rgb led functions pointers
fp rgb_fnct_pntrs[] = {&rgb_brightness,&red_brightness,&green_brightness,&blue_brightness,&rgb_on_time,&rgb_breath};
//led function pointers
fp led1_fnct_pntrs[] = {&led1_brightness,&led1_on_time};
fp led2_fnct_pntrs[] = {&led2_brightness,&led2_on_time};
//store list of ponters to peripheral function pointer lists
fp *perph_fnct_pntr_pntr[] = {rgb_fnct_pntrs, led1_fnct_pntrs, led2_fnct_pntrs};
//store pointers linking peripheral name index to list of function names
p name_to_fnct_lst[3]= {&rgb_fnct_names,&led1_fnct_names,&led2_fnct_names};
我不确定是什么导致了这个问题,所以任何帮助将不胜感激。
解决方案
我猜它的工作方式是,你从一个字符串开始,通过迭代找到匹配的字符串name_to_fnct_lst[]
,然后搜索它指向的数组(rgb_fnct_names
, led1_fnct_names
, led2_fnct_names
)。匹配时,您有两个索引(函数列表索引和列表中的名称)。
您使用第一个索引在 中查找函数指针列表,然后使用第二个索引在、或perph_fnct_pntr_pntr
中查找索引。rgb_fnct_pntrs
led1_fnct_pntrs
led2_fnct_pntrs
这适用于 rgb 情况,因为rgb_fnct_names
和rgb_fnct_pntrs
都有 6 个条目,但不适用于 led1/2 因为led1_fnct_names
和led2_fnct_names
有 3 个条目,但led1_fnct_pntrs
和led2_fnct_pntrs
有 2 个条目。我是否正确遵循?
如果是这样,看起来解决方案是将缺少的函数指针添加到led1_fnct_pntrs
and led2_fnct_pntrs
。或者它可能会简化将数组组合成一个数组的事情char[3][6][20]
(fp[3][6]
在第一种情况下没有缺点,无论如何您都在分配未使用的字符,第二种情况会丢失一些未使用的指针地址,您可以从较小的代码中获得这些地址)。
另一种构造它的方法是:
struct f_nam_ptr {
fp func;
char name[20];
};
// Using a single map array here, or split it
// into rgb, led1, led2 maps.
struct f_nam_ptr f_nam_ptr_map[] = {
{ &rgb_brightness, "rgb_brightness" },
// etc...
};
这样可以确保每个名称都有一个匹配的指针(并且不会浪费太多内存)。
推荐阅读
- php - 替换多个字符串或文本
- java - 以编程方式创建 2D ArrayList,然后从中创建单个 ArrayList
- c# - 我的视觉工作室(2019)没有显示错误来自哪里
- java - [Ljava.lang.Object; 不能转换为 java.util.Collection
- python - AttributeError:“RepeatedComposite”对象没有属性“描述”
- r - X 轴标签未在 R 上的基础绘图系统上打印
- c# - 从分隔符分隔的字符串中提取子字符串
- r - 将字符从列名的开头移动到列名的结尾(附加问题)
- openedge - 如果我不在程序中使用索引字段怎么办?
- javascript - onsubmit = "function()" 在表单上不起作用