我是编程新手,正在尝试在C ++上实现A星搜索算法。我有分段错误:11因为没有初始化我的指针。我试过几种不同的方法无济于事。 我仍然对整个指针和动态内存分配概念感到困惑。
任何人都可以帮我搞清楚吗?谢谢。
#include <iostream>
#include <vector>
#include <fstream>
#include <math.h>
#include <stdio.h>
#include <string>
#include <vector>
#include <iostream>
#include <fstream>
using namespace std;
// Definition of the heuristic. The heuristic in this problem is the distance between
// two coordinates
double heuristic(double x1, double y1, double x2, double y2) {
double dx, dy;
dx = x1 - x2;
dy = y1 - y2;
return sqrt(dx*dx - dy*dy);
//return sqrt(pow((x1 - x2), 2) + pow((y1 - y2), 2));
}
// ----- A Star Search Algorithm (f = g + h)----
double** a_star_search(double points[][2]) {
int count = 1;
double** points1 = NULL;
// points1[10][2];
double x1 = points[0][0];
double y1 = points[0][1];
points1[count - 1][0] = x1;
points1[count - 1][1] = y1;
while (count <= 10) {
double tempx1;
double tempy1;
double distance = 10000000;
for (int i = 0; i < 10; i++) {
if (points[i][0] != 0 && points[i][1] != 0) {
double distance2 = heuristic(x1, y1, points[i][0], points[i][1]);
if (distance2 < distance) {
tempx1 = points[i][0];
tempy1 = points[i][1];
distance = distance2;
}
}
}
x1 = tempx1;
y1 = tempy1;
count++;
points1[count - 1][0] = x1;
points1[count - 1][1] = y1;
}
return points1;
}
int main() {
double points[7][2];
int counter = 0;
ifstream infile("waypoints.txt");
int a, b;
while (infile >> a >> b)
{
points[counter][0] = a;
points[counter][1] = b;
counter++;
}
points[6][0] = points[0][0];
points[6][1] = points[0][1];
double** points1 = a_star_search(points);
cout << "Initial Sequence: ";
for (int i = 0;i < 7;i++) {
cout << "(" <<points[i][0] << " , " << points[i][1] << "), ";
}
cout << "\n\nOptimized Sequence: ";
for (int i = 0;i < 7;i++) {
cout << "(" << points1[i][0] << " , " << points1[i][1] << "), ";
}
cout << "\n\nTotal Distance after A* search: ";
double totaldistance = 0;
for (int i = 0;i < 6;i++) {
double dis = heuristic(points1[i][0], points1[i][1], points1[i + 1][0], points1[i + 1][1]);
cout << dis << "+";
totaldistance = totaldistance + dis;
}
cout<< "=" << totaldistance <<endl;
}
答案 0 :(得分:0)
在您的a_star_search函数中将double** points1
变量设置为NULL
之后,您没有为std::vector
变量动态分配内存。正如@ user4581301所指出的,使用int operation;
/* int for storing a string? huh?
* or were you thinking about function pointers ?
* Normally you would use a char[]
*/
scanf(" %s", operation);
/* Using %s specifier looks weird .
* Also scanf is reading into operation and not &operation
* So is having a space in the in the beginning of the format string.
*/
int addition;
/* Automatic variables are not initialized as per the standard
* But what about the type?
* Were you intending to do something like char addition[]="addition"
*/
if(operation = addition)
/* If you somehow manage to get to this point
* you have another problem you do an assignment in the statement using =
* You should have been using ==
*/
。这将显着简化您的代码,并值得花时间学习STL容器。