从指向字节的指针数组中获取特定字节数组的大小

3
在下面的示例C代码中,用于Arduino项目,我正在寻找获取指向字节数组的指针数组中特定字节数组大小的能力,例如:
    void setup()
    {
      Serial.begin(9600); // for debugging

      byte zero[] = {8, 169, 8, 128, 2,171,145,155,141,177,187,187,2,152,2,8,134,199};
      byte one[]  = {8, 179, 138, 138, 177 ,2,146, 8, 134, 8, 194,2,1,14,199,7, 145, 8,131, 8,158,8,187,187,191};
      byte two[] = {29,7,1,8, 169, 8, 128, 2,171,145,155,141,177,187,187,2,152,2,8,134,199, 2, 2, 8, 179, 138, 138, 177 ,2,146, 8, 134, 8, 194,2,1,14,199,7, 145, 8,131, 8,158,8,187,187,191};

      byte* numbers[3] = {zero, one, two };

      function(numbers[1], sizeof(numbers[1])/sizeof(byte)); //doesn't work as desired, always passes 2 as the length
      function(numbers[1], 25); //this works
    }

    void loop() {
    }

    void function( byte arr[], int len )
    {
      Serial.print("length: ");
      Serial.println(len);
      for (int i=0; i<len; i++){
        Serial.print("array element ");
        Serial.print(i);
        Serial.print(" has value ");
        Serial.println((int)arr[i]);
      }
    }

在这段代码中,我明白sizeof(numbers[1])/sizeof(byte)无法工作,因为numbers[1]是一个指针而不是字节数组的值。
在这个例子中,是否有一种方法可以在运行时获取指向字节的指针数组中特定(在运行时确定)字节数组的长度?请注意,我只能在Arduino环境中使用C(或汇编语言)进行开发。
此外,也可以考虑其他建议,而不是指向字节的指针数组。总体目标是组织字节列表,这些列表可以在运行时检索到其长度。

你打算在运行时如何获取这个字节数组?它是从外部设备或文件中读取的吗?还是它将始终是在代码中声明的数组。如果是代码,那么ndim的解决方案将起作用。如果是外部的,你将已经有了一些大小的信息来自于读取文件/源以便为你的动态数组分配大小,对吧? - Michael Dorgan
一切都在代码中设置好了。外部驱动程序是一个计时器,特定的字节数组在特定的时间使用,以使语音合成器说出与当前时钟计时器值相适应的内容。 - Pat James
1个回答

3
void setup(void)
{
    ...

    byte* numbers[3] = {zero, one, two };
    size_t sizes[3] = {sizeof(zero), sizeof(one), sizeof(two)};

    function(numbers[1], sizes[1]);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接