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

时间:2010-04-23 00:01:29

标签: c arduino

在以下示例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(或汇编)。

同样对其他建议开放,而不是指向字节的指针数组。总体目标是组织字节列表,可以在运行时检索长度。

1 个答案:

答案 0 :(得分: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]);
}
相关问题