1

我已经成功地为输入文件构建了一个邻接矩阵,输入的第一行作为顶点的总数,以下几行是任意顺序的边作为顶点对。例如

文件.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);
}

非常感谢任何和所有帮助:)

4

2 回答 2

0

我认为问题出在您的构建中:

tree * buildAdjList(int a[][100], int n)
{       int i, j, k;
    tree *node;
    tree * adjArray[n];
    // work
    return adjArray[0];
}

您正在尝试从局部变量(失去作用域)返回内存。在上面的代码中,tree * adjArray[n]创建了一个局部变量数组(在本地地址空间中)。函数离开后返回指向该数组头部的指针将无效。

通常,当你想创建一个列表或节点时,你需要 malloc 以便内存将存在于堆中(因此将超过 create 函数本身)。就像是:

tree * buildAdjList(int a[][100], int n)
{
    tree *newtree = malloc(n * sizeof(tree *));
    // work
    return newtree;
}

tree *请注意,您正在分配's 而不是 full的连续内存块(读取:数组)trees

于 2013-03-18T02:17:43.280 回答
0

我意识到这是一个老问题,但我立即发现你在做循环计数器的方式存在问题。由于这是 C++,大小为 n 的数组中的元素是 arr[0]、arr[1]、... arr[n-1]。您的代码引用了超出数组边界的 arr[n] 并可能导致崩溃。

您的循环逻辑需要如下所示,以便在迭代中不包含 i=n,方法是在 for 循环测试中使用 < 而不是 <=:

for (i = 0; i < n; i++)
    adjArray[i] = NULL;
于 2017-03-05T02:29:10.113 回答