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];
}
}
}
}
请帮助......
I am getting a segmentation fault in the following code:
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];
}
}
}
}
PLease Help.....
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
作为一种完全盲目的猜测,没有 2 个数组的声明,这是由寻址它们的一个错误引起的。
j<=2
应为j<2
和/或count=1
应为count=0
。只是我在心理调试方面的尝试。更新:新版本并没有变得更加清晰——你喜欢留下太多的想象空间。没有对 insertNode 的调用,因此任何取消引用pointerArray 的尝试都可能出现段错误。这是问题中的拼写错误,还是您所看到的段错误的原因?另外,最外面的循环从 1 迭代到 7 - 这应该对应于pointerArray 吗?如果是这样,如果您要调用 insertNode 并将 i 作为第二个参数传递,则 0 - 6 可能更有意义。你有可以编译的代码吗?
As a completely blind guess, without the declarations of the 2 arrays, caused by an off by one error addressing them. Either
j<=2
should bej<2
and/orcount=1
should becount=0
. Just my attempt at psychic debugging.Update: New version is not much clearer - you like to leave way too much to the imagination. There are no calls to insertNode, so any attempt to deref pointerArray may seg-fault. Is that a typo in the question, or the cause of the seg-fault you're seeing? Also, the outermost loop iterates from 1 to 7 - is that supposed to correspond to the pointerArray? If so, 0 - 6 might make more sense if you're going to call insertNode passing i as the second param. Do you have code that compiles?