gpt4 book ai didi

c - 如何定义任意大小的二维数组,然后在编译时确定其维度?

转载 作者:行者123 更新时间:2023-12-02 08:57:30 27 4
gpt4 key购买 nike

执行摘要:

  1. 如何在 C 中定义任意大小的二维数组?
  2. 如何在编译时确定该数组的维度?

全面披露:

我正在为嵌入式 Controller 编写代码。我的应用程序需要多个不同大小的查找表,这些查找表将全部由一个查找函数(二分搜索)使用。这是我到目前为止所拥有的:

typedef struct
{
unsigned char count; // number of rows in the table
unsigned char width; // number of bytes in each row
const unsigned char * data; // pointer to table data[count][width]
}
LookupTable;

// returns the index of a value from within a table
unsigned char Lookup(unsigned long value, const LookupTable * table);

这部分正在工作。我现在想做的是在我的源代码中定义这些表,而不必手动输入 countwidth 常量。这是我现在正在做的事情:

#define T1_count 100
#define T1_width 3
const unsigned char table1_data[T1_count][T1_width] =
{
{ 0x12, 0x34, 0x56 },
{ 0x12, 0x38, 0x12 },
...
};

const LookupTable table1 = { T1_count, T1_width, table1_data };

这是我希望能够做的事情(伪代码,因为这个数组定义实际上不会编译):

const unsigned char table1_data[] = 
{
{ 0x12, 0x34, 0x56 },
{ 0x12, 0x38, 0x12 },
...
};

const LookupTable table1 =
{
get_count_expr(table1_data),
get_width_expr(table1_data),
table1_data
};

显然,get_count_exprget_width_expr 必须是某种基于表大小的常量表达式,而不是实际的函数调用。

需要明确的是,该设计的任何部分都不是一成不变的。我只是发布到目前为止我所拥有的内容,希望我的意图是明确的。任何改进的想法将不胜感激。

“为什么”:

这些表会经常更改,如果可以添加和删除条目,或者更改表的宽度而不必每次都手动调整常量,那么维护会更容易。必须手动跟踪尺寸可能容易出错并且违反 DRY 。我正在寻找更好的方法。

最佳答案

嗯...您可以将最左边的大小留给编译器:

#define T1_WIDTH 3
const unsigned char table1_data[][T1_WIDTH] =
{
{ 0x12, 0x34, 0x56 },
{ 0x12, 0x38, 0x12 },
/* ... */
};
T1_count = sizeof table1_data / sizeof *table1_data;
T1_width = sizeof *table1_data;

关于c - 如何定义任意大小的二维数组,然后在编译时确定其维度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3843246/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com