2016-04-23 70 views
0

我是編程新手,正試圖在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

你試過很多方法嗎?分配動態數組?如果你看,你會發現如何做到成千上萬的地方,但不要打擾。試一試'std :: vector'而不是動態數組。爲您節省很多麻煩。 – user4581301

回答

0

您還沒有動態地double** points1變量在a_star_search功能,將其設置爲NULL後分配內存。正如@ user4581301所指出的,使用std::vector。這將顯着簡化您的代碼,並且值得花時間學習STL容器。