Kruskal 알고리즘을 구현 중입니다.C : 재 할당하지 않고 변수 값이 변경됨
다음 코드에서 graph()를 호출하면 노드 값이 변경됩니다. 나는 왜 그런지 잘 모르겠다 - 누군가가 이것을 정리할 수 있다면 나는 그것을 크게 고맙게 생각할 것이다. 그래프 내에서 노드 값에 액세스하지 않고 두 노드 모두 & 에지에 액세스하는 배열이 스택 외부에 할당됩니다!
struct node {
int parent, rank;
};
typedef struct node node;
struct edge {
int fromvertex, tovertex;
float weight;
};
typedef struct edge edge;
node* nodes;
edge* edges;
typedef enum {Unvisited, Visited} vertexstate;
int main (int argc, char const *argv[])
{
void getcount(int*, int*);
void graph(int, int);
void makeset(int);
int hasspantree(int, int, int);
void kruskal(int, int);
int printmcst(int);
int nodecount, edgecount, i, totalcost=0;
getcount(&nodecount, &edgecount);
for (i = 1; i <= nodecount; i++)
makeset(i);
printf("%d \t %d\n", nodes[6].parent, nodes[6].rank);
graph(nodecount, edgecount);
printf("%d \t %d\n", nodes[6].parent, nodes[6].rank);
printf("Has a spanning tree?");
if(hasspantree(1, nodecount, edgecount)) {
printf("\t Yes.\n");
kruskal(nodecount, edgecount);
printf("MCST found:\n\n");
totalcost = printmcst(nodecount);
printf("\nCost: %d", totalcost);
}
else {
printf("No.");
exit(0);
}
return 0;
}
void graph(int nodecount, int edgecount)
{
for (int i = 0; i < edgecount; i++) {
scanf("%d", &edges[i].fromvertex);
scanf("%d", &edges[i].tovertex);
scanf("%f", &edges[i].weight);
}
}
void getcount(int *nodecount, int *edgecount)
{
scanf("%d", nodecount);
scanf("%d", edgecount);
nodes = malloc(*nodecount * sizeof(node));
edges = malloc(*edgecount * sizeof(edge));
}
void makeset(int x)
{
nodes[x].parent = x;
nodes[x].rank = 0;
}
에 액세스 할 때이 버퍼 오버런을 일으킬 것인가? – unxnut
@unxnut in makeet, 나는 모든 노드의 싱글 톤 세트를 만든다. 나는 원래 게시물을 수정하여 makeet()을 포함 시켰습니다. – michaelwayman
모든 함수 프로토 타입은 main() 함수의 외부/앞에 있어야하므로 컴파일러는 선언 및 해당 함수에 대한 호출에 대해 기대할 수있는 사항을 알고 있습니다. 그렇지 않은 경우, main() 함수 내의 프로토 타입을 사용하면 프로토 타입이 '범위를 벗어났습니다.'따라서 main() 함수의 한계를 넘어 존재하지 않습니다. – user3629249