2011-05-03 121 views
-1

我得到下面的代码段故障:C++分割故障for循环

Node *pointerArray[6]; 
    int onesNeighbor[]={2,3,6}; 

    Node *createNode(int localDistance)//////creates a node 
    { 
Node *newNode; 
newNode=new Node; 
newNode->wasVisited=false; 
newNode->shortestDistance=localDistance; 


return newNode; 
    } 

    void insertNode(Node *n,int i)//////////////////connects nodes to the 
    {/////////////////////////////////////////array of pointers 
    pointerArray[i]=n; 
    } 


for(i=1;i<7;i++) 
{ 
    if(i==1){ 
    n=createNode(0); 
    cout<<i<<"\t"<<n->shortestDistance<<"\t"; 
    for(int j=0;j<=2;j++) 
    cout<< onesNeighbor[j]<<","; 
    cout<<endl; 


    for (count = 1; count < 2; count++) 
    { 
    current = pointerArray[count]; 

    if (count == 1) 
    { 
     for (int j = 0; j <= 2; j++) 
     { 
      lowest = current->shortestDistance; 
      current = pointerArray[onesNeighbor[j]]; 

      if (current->shortestDistance < lowest) 
      { 
       lowest = current->shortestDistance; 
       closestNeighbor = onesNeighbor[j]; 
      } 
     } 
     } 
     } 

请帮助.....

+2

线段故障发生在哪条线上? – TheFuzz 2011-05-03 00:53:23

+2

我们需要看到'pointerArray'和'onesNeighbor'的声明能够准确地告诉你,但基本上,其中一个数组要么太小,要么是一个野指针 - 可能是后者。 – 2011-05-03 00:53:30

+0

当前写入的COde永远不会到达内部循环,因为在第一次迭代开始时count将为2。 – Joe 2011-05-03 01:45:23

回答

4

作为一个完全失明的猜测,而2个阵列的声明,由于一次错误导致它们失败而导致。 j<=2应该是j<2和/或count=1应该是count=0。只是我尝试进行心理调试。

更新:新版本没有更清晰 - 你喜欢留下太多的想象力。没有调用insertNode,所以任何尝试deref指针数组可能seg-fault。这是问题中的错字,还是您看到的seg-fault的原因?另外,最外层的循环从1到7迭代 - 是否应该对应于pointerArray?如果是这样,如果你打算调用insertNode作为第二参数传递i,那么0-6可能更有意义。你有编译的代码吗?