入力の最初の行を頂点の総数として、入力ファイルの隣接行列を正常に作成しました。次の行は、頂点のペアとして任意の順序でエッジです。例えば
file.txt
7
1 2
4 6
4 3
5 2
ただし、このプログラムを実行すると、隣接行列は正常に構築されますが、構造体ツリーの配列として隣接リストを作成しようとすると、プログラム Seg が失敗します (コア ダンプ)。プログラムが失敗する理由についての手がかりはありますか? 問題の関数は次のとおりです。
tree * buildAdjList(int a[][100], int n)
{ int i, j, k;
tree *node;
tree * adjArray[n];
for(i=0; i<=n; i++)
adjArray[i] = NULL;
for(j=0; j<=n; j++)
for(k=0; k<=n; k++)
if(a[j][k] == 1){
node = (tree *)malloc(sizeof(tree));
node->val = k;
node->next = adjArray[j];
adjArray[j] = node;
}
return adjArray[0];
}
プログラムの残りの部分:
#include <stdio.h>
#include <stdlib.h>
struct tree{
int val;
struct tree *next;
};
typedef struct tree tree;
void printArray(int a[][100],int n);
void adjacencyMatrix(int a[][100], int n, int p1, int p2, FILE * inputF);
tree * buildAdjList(int a[][100], int n);
void printAdjArray(tree * adjArr[], int n);
int main(int argc, char ** argv)
{
int a[100][100];
int n,*q;
FILE * inputFile;
int entries, i;
inputFile = fopen(argv[1], "r");
int p1, p2 =0;
if(inputFile==NULL){
printf("File failed to open.");
exit(EXIT_FAILURE);
}
fscanf(inputFile, "%d", &entries);
tree * adjarray[entries];
q = (int *)malloc(sizeof(int)*n);
adjacencyMatrix(a,entries,p1,p2,inputFile);
adjarray[0] = buildAdjList(a, entries);
printAdjArray(adjarray, entries);
return 0;
}
void adjacencyMatrix(int a[][100], int n, int p1, int p2, FILE * inputF){
int i,j;
do{
for(i = 0;i <= n; i++)
{
for(j = 0;j <=n; j++)
{ if(i==p1 && j == p2){
a[i][j] = 1;
a[j][i] = 1;
}
}
a[i][i] = 0;
}
}while(fscanf(inputF, "%d %d", &p1, &p2) !=EOF);
printArray(a,n);
}
ありとあらゆる助けが大歓迎です:)