...调试时出现了unhandled exception in access violation,但是编译...
发布网友
发布时间:2024-10-24 02:30
我来回答
共1个回答
热心网友
时间:2024-11-04 12:03
三个地方会报错
1:59行,printf("最小生成树的权:f%\n",cost);中应该为%f。
解决方法:你写错了,这样也会造成访问非法内存。
2:60行,delete释放内存时元素大小不定,因为你前面new 时,nodenum并没有赋值。
解决方法:应该将赋值语句
printf("请输入分支数目:\n");
scanf("%d",&edgenum);
printf("请输入节点数目:\n");
scanf("%d",&nodenum);
提前到new前,像这样
...
printf("请输入分支数目:\n");
scanf("%d",&edgenum);
printf("请输入节点数目:\n");
scanf("%d",&nodenum);
p=new EDGE[edgenum+1];
q=new int[nodenum+1];
int i=0;
int j=0;
...
3:p释放的问题同上。
附上修正后的代码:
#include <stdio.h>
typedef struct//
{
int start;
int end;
float weight;
}EDGE;
int edgenum,nodenum;
EDGE *p;
int *q;
void setfather(int edge);
int findfather (int node);
int main()
{
printf("请输入分支数目:\n");
scanf("%d",&edgenum);
printf("请输入节点数目:\n");
scanf("%d",&nodenum);
p=new EDGE[edgenum+1];
q=new int[nodenum+1];
int i=0;
int j=0;
for(i=0;i<=edgenum;i++)
{
p[i].start=0;
p[i].end=0;
p[i].weight=0;
}
for(i=0;i<=nodenum;i++)
q[i]=i;
for(i=1;i<=edgenum;i++)
{
printf("第%d条边的始节点:\n",i);
scanf("%d",&p[i].start);
printf("第%d条边的末节点:\n",i);
scanf("%d",&p[i].end);
printf("第%d条边的权值:\n",i);
scanf("%f",&p[i].weight);
}
EDGE temp={0,0,0.00};
for(i=edgenum;i>=2;i--)//冒泡排序
{
for(j=2;j<=i;j++)
{
if(p[j-1].weight>p[j].weight)
{
temp=p[j];
p[j]=p[j-1];
p[j-1]=temp;
}
}
}
printf("加的新边:%d--%d\n",p[1].start,p[1].end);
float cost=p[1].weight;
setfather(1);
for(i=2;i<=edgenum;i++)
{
if(findfather(p[i].start)!=findfather(p[i].end))
{
cost=cost+p[i].weight;
setfather(i);
printf("加的新边:%d--%d\n",p[i].start,p[i].end);
}
}
printf("最小生成树的权:%f\n",cost);
delete []q;
delete []p;
q=0;
p=0;
return 0;
}
void setfather(int edge)
{
int snode =findfather(p[edge].start);
int enode =findfather(p[edge].end);
if (enode<snode)
q[snode]=enode;
else
q[enode]=snode;
}
int findfather (int node)
{
while (node!=q[node])
node=q[node];
return node;
}