代码之家  ›  专栏  ›  技术社区  ›  Pat James

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

  •  3
  • Pat James  · 技术社区  · 14 年前

    在下面的示例c代码中,用于 Arduino project,我正在寻找在指向字节的指针数组中获取特定字节数组大小的能力,例如

        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 回复  |  直到 14 年前
        1
  •  3
  •   ndim    14 年前
    void setup(void)
    {
        ...
    
        byte* numbers[3] = {zero, one, two };
        size_t sizes[3] = {sizeof(zero), sizeof(one), sizeof(two)};
    
        function(numbers[1], sizes[1]);
    }