[英]How can I fix the “Invalid memory reference” error in my code?
I'm working on a maze-solver robot for my arduino project. 我正在为arduino项目开发迷宫求解器机器人。 I want my robot to memorize the maze and then find the shortest path.
我希望我的机器人记住迷宫,然后找到最短的路径。 I keep having a problem when the char array's lenght is 3.
当char数组的长度为3时,我一直遇到问题。
The problem appears when the lenght is <= 3, so I tried diffrent stuff to make a particular case out of that, that's why the if (strlen(a) > 3)
is there. 当长度小于等于3时出现问题,因此我尝试了不同的方法来制作一个特殊的案例,这就是为什么
if (strlen(a) > 3)
在那的原因。
#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;
int main()
{
char a[] = "LLLBLLLRBLLBSRSRS";
char b[200];
while(strcmp(a, b) != 0) {
strcpy(b, a); //sa verific daca se schimba sirul, daca nu inseamna ca a ajuns la minim
for(int i = 0; i < strlen(a) - 2; i++)
{
if(a[i] == 'L' && a[i + 1] == 'B' && a[i + 2] == 'R') //if urile astea cauta combinatii de cate 3 miscari sa optimizezi drumul
{
a[i] = 'B';
if (strlen(a) > 3) strcpy(a + i + 1, a + i + 3);
else a[i + 1] = '\0';
}
else if(a[i] == 'L' && a[i + 1] == 'B' && a[i + 2] == 'S')
{
a[i] = 'R';
if (strlen(a) > 3) strcpy(a + i + 1, a + i + 3);
else a[i + 1] = '\0';
}
else if(a[i] == 'L' && a[i + 1] == 'B' && a[i + 2] == 'L')
{
a[i] = 'S';
if (strlen(a) > 3) strcpy(a + i + 1, a + i + 3);
else a[i + 1] = '\0';
}
else if(a[i] == 'S' && a[i + 1] == 'B' && a[i + 2] == 'L')
{
a[i] = 'R';
if (strlen(a) > 3) strcpy(a + i + 1, a + i + 3);
else a[i + 1] = '\0';
}
else if(a[i] == 'S' && a[i + 1] == 'B' && a[i + 2] == 'S')
{
a[i] = 'B';
if (strlen(a) > 3) strcpy(a + i + 1, a + i + 3);
else a[i + 1] = '\0';
}
else if(a[i] == 'R' && a[i + 1] == 'B' && a[i + 2] == 'L')
{
a[i] = 'B';
if (strlen(a) > 3) strcpy(a + i + 1, a + i + 3);
else a[i + 1] = '\0';
}
}
cout << a << endl;
}
return 0;
}
This is the output: 这是输出:
LLSLLBRRSRS LLSLBRSRS LLSBSRS LLBRS LBS LLSLLBRRSRS LLSLBRSRS LLSBSRS LLBRS LBS
and then the error message Runtime error(Exit status:139(Invalid memory reference)). 然后出现错误消息运行时错误(退出状态:139(无效的内存引用))。
The goal is to make the last output be R, because LBS means R. Thanks for the attention! 目标是使最后一个输出为R,因为LBS表示R。感谢您的关注!
The reason for invalid memory reference is in the loop consition: 无效的内存引用的原因在于循环条件:
for(int i = 0; i < strlen(a) - 2; i++)
you are accessing a[i + 2]
inside loop so the last iteration must end at i < strlen(a) - 3
: 您正在循环中访问
a[i + 2]
,因此最后一次迭代必须在i < strlen(a) - 3
:
for(int i = 0; i < strlen(a) - 3; i++)
this just fixes your memory problem. 这只是解决您的内存问题。 you still get
LBS
as the last output. 您仍然会得到
LBS
作为最后的输出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.