Arduino 使用.substring方法时出现ESP32 Guru冥想错误

Arduino 使用.substring方法时出现ESP32 Guru冥想错误,arduino,esp32,Arduino,Esp32,因此,我已经使用Arduino IDE为我的ESP32编写了一个函数,并且我需要编写一个函数来获取十六进制值的组合字符串,如下所示: ffffff0000ffff0000 {"ffffff","0000ff","ff0000"} for(int i = 0; i < input.length(); i += 6){ Serial.println(input.substring(i,i+6)); }; 并将其拆分

因此,我已经使用Arduino IDE为我的ESP32编写了一个函数,并且我需要编写一个函数来获取十六进制值的组合字符串,如下所示:

ffffff0000ffff0000
{"ffffff","0000ff","ff0000"}
for(int i = 0; i < input.length(); i += 6){

    Serial.println(input.substring(i,i+6));
  };
并将其拆分为一个数组,如下所示:

ffffff0000ffff0000
{"ffffff","0000ff","ff0000"}
for(int i = 0; i < input.length(); i += 6){

    Serial.println(input.substring(i,i+6));
  };
到目前为止,我写了以下内容:

String colorIndex[] = {};

void processColors(String input){

  int count = 0;
  
  for(int i = 0; i < input.length(); i += 6){

    colorIndex[count] = input.substring(i,i+6);
    count++;
  };

  for(int i = 0; i < sizeof(colorIndex); i++){
    Serial.println(colorIndex[i]);
  }
  
}

我在谷歌上搜索了一下,发现这个错误是由非法访问内存引起的。这是什么原因造成的?我能做些什么来修复它?或者,有没有更好的方法来完成我希望完成的任务?

您将
colorIndex
定义为
字符串的空数组

String colorIndex[] = {};
成为一个空数组,然后开始在其中存储内容。。。但是你没有预订任何地方来存放它们。因此,当您尝试在循环中保存
colorIndex
子字符串时,它被随机写入某个位置,并导致您看到的异常

您可以通过如下方式取消分配来轻松验证这一点:

ffffff0000ffff0000
{"ffffff","0000ff","ff0000"}
for(int i = 0; i < input.length(); i += 6){

    Serial.println(input.substring(i,i+6));
  };
为了防止代码意外溢出数组,您应该真正测试循环中的索引。在这种情况下,您的代码应该更像:

#define MAX_COLOR_INDICES 3

String colorIndex[MAX_COLOR_INDICES] = {};


void processColors(String input){

  int count = 0;
  
  for(int i = 0; i < input.length(); i += 6){
    if(count == MAX_COLOR_INDICES) {
      Serial.printf("ran out of room for color indices at %d\n", count);
      break;
      }

    colorIndex[count] = input.substring(i,i+6);
    count++;
   };
#定义最大颜色索引3
字符串颜色索引[最大颜色索引]={};
void processColors(字符串输入){
整数计数=0;
对于(int i=0;i