因此,我已经使用Arduino IDE为我的ESP32编写了一个函数,并且我需要编写一个函数来获取十六进制值的组合字符串,如下所示:
ffffff0000ffff0000并将其拆分成一个数组,如下所示:
{"ffffff","0000ff","ff0000"}到目前为止,我写了以下内容:
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]);
}
}但是,我遇到了一个问题,无论何时运行此函数,串行端口都会打印出以下错误:
Guru Meditation Error: Core 1 panic'ed (StoreProhibited). Exception was unhandled.
Core 1 register dump:
PC : 0x4000c3f5 PS : 0x00060830 A0 : 0x800d9575 A1 : 0x3ffd2eb0
A2 : 0x00000050 A3 : 0x3ffd2f10 A4 : 0x00000007 A5 : 0x0000ff00
A6 : 0x00ff0000 A7 : 0xff000000 A8 : 0x00000000 A9 : 0x00000050
A10 : 0x00000066 A11 : 0x3ffd3696 A12 : 0x00000007 A13 : 0xed62d3d8
A14 : 0x06000000 A15 : 0x06000000 SAR : 0x00000010 EXCCAUSE: 0x0000001d
EXCVADDR: 0x00000050 LBEG : 0x400014fd LEND : 0x4000150d LCOUNT : 0xfffffffe
Backtrace: 0x4000c3f5:0x3ffd2eb0 0x400d9572:0x3ffd2ed0 0x400d967a:0x3ffd2ef0 0x400d1283:0x3ffd2f10 0x400d1322:0x3ffd2f40 0x400d7345:0x3ffd2f80 0x400d51e9:0x3ffd2fc0 0x400d5279:0x3ffd3000 0x400d8369:0x3ffd3020 0x400d83e9:0x3ffd3060 0x400d89fa:0x3ffd3080 0x40088b7d:0x3ffd30b0
Rebooting...我用谷歌搜索了一下,发现这个错误是由对内存的非法访问引起的。是什么导致了这个问题?我能做些什么来修复它?或者,有没有更好的方法来完成我想要完成的任务?
发布于 2020-10-11 05:18:47
您将colorIndex定义为String的空数组。
String colorIndex[] = {};成为一个空数组,然后你开始在其中存储数据...但是你还没有预留任何地方来存放它们。因此,当您尝试在循环中保存colorIndex子字符串时,它会随机写在某个地方,并导致您看到的异常。
只需像这样取消赋值,就可以轻松地验证这一点:
for(int i = 0; i < input.length(); i += 6){
Serial.println(input.substring(i,i+6));
};您应该会看到您提取的子字符串,并且不会得到错误。
您需要声明colorIndex,以便有足够的空间来存储任何要在其中存储的项。例如,如果你知道你的字符串永远不会超过3个,你可以这样写:
String colorIndex[3] = {};为了防止您的代码意外地溢出数组,您应该真正测试循环中的索引。在这种情况下,您的代码应该看起来更像:
#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++;
};https://stackoverflow.com/questions/64297880
复制相似问题