gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 00:40:40 24 4
gpt4 key购买 nike

在以下示例 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(或汇编)语言进行开发。

除了指向字节的指针数组之外,还可以接受其他建议。总体目标是组织可以在运行时按长度检索的字节列表。

最佳答案

void setup(void)
{
...

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

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

关于c - 从指向字节的指针数组中获取特定字节数组的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2695358/

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