首页 > 解决方案 > 在c中的编译时确定数组中的位置

问题描述

有没有办法在 c 的编译时确定 const 数组中的位置?这是我正在尝试做的一个例子:

const unsigned char DATA[] = {
// Part 1 
// hundreds or thousands of values

// Part 2  
// compiler records this position in the array in PART2
// hundreds or thousands of values

// Part 3  
// compiler records this position in the array in PART3
// hundreds or thousands of values

// ...
};

const unsigned int PART_IDX [] = {
// index to Part 1
0,

// index to Part 2
PART2,

// index to Part 3
PART3,

// ...
};

我可以在运行时计算索引,但宁愿它们已经完成,因为数组是恒定的。我可以制作一个程序来分析源代码,计算每个部分中的元素数量,并将数据插入 PART_IDX,但我真的希望编译器在编译时执行此操作。这样,如果数据被插入或删除,或者部分被添加或删除,编译器仍然会生成正确的代码。有人知道我该怎么做吗?谢谢!

编辑:为了澄清,使用带有实际数据的示例:

const unsigned char DATA[] = {
// Part 1 
0, 1, 2, 3, 4,

// Part 2  
// compiler records this position in the array in PART2 (should be 5)
10, 11, 12, 13, 14, 15, 16,

// Part 3  
// compiler records this position in the array in PART3 (should be 12)
20, 21, 22
};

const unsigned int PART_IDX [] = {
// index to Part 1
0,

// index to Part 2
PART2,   // should be 5, points to 10 in the array

// index to Part 3
PART3,   // should be 12, points to 20 in the array
};

问题是,我可以用什么来代替以让编译器在and// compiler records this position ...中记录适当值的行?PART2PART3

标签: c

解决方案


与其试图让 C 做一些它不应该做的事情,更好和更常见的方法是通过编写一个准备数据的程序来为 C 程序准备数据。也就是说,编写一些其他程序来计算部件中的数据并编写初始化DATA和初始化所需的 C 代码PART_IDX

另一种选择是:

  • 将每个部分的所有数据放在一个单独的“.h”文件中,例如文件“part1.h”、“part2.h”、“part3.h”。
  • 要进行初始化DATA,请将所有这些头文件包含在其初始化列表中。
  • 要计算部分的索引,请使用sizeof计算包含前面部分的代理数组中的元素数。

例子:

“part1.h”包含10, 11, 12,.

“part2.h”包含20, 21,.

“part3.h”包含30, 31, 32, 33,.

C文件是:

const unsigned char DATA[] =
{
    #include "part1.h"
    #include "part2.h"
    #include "part3.h"
};


const unsigned int PART_IDX [] =
{
    0,

    sizeof (const unsigned char []) {
        #include "part1.h"
    } / sizeof (const unsigned char),

    sizeof (const unsigned char []) {
        #include "part1.h"
        #include "part2.h"
    } / sizeof (const unsigned char),
};


#include <stdio.h>


int main(void)
{
    for (int i = 0; i < 3; ++i)
        printf("Part %d begins at index %d with value %d.\n",
            i, PART_IDX[i], DATA[PART_IDX[i]]);
}

推荐阅读