注: 「.」は使用できません。およびグラフ上の '->' 演算子。そのため、これらのマクロを使用します。
次のグラフの宣言 (私は変更できません - 代入なので、それについては何も聞かないでください) については、
#include <stdio.h>
#include <stdlib.h>
#define TAG(vp) ((vp)->tag)
#define LABEL(vp) ((vp)->label)
#define EDGE(vp) ((vp)->edge)
typedef struct vertex
{
char tag; /* can be used for any puproses; haven't used though */
char *label;
struct vertex *edge[1];
}
vertex, *vp;
グラフの隣接リストを作成する次の構造と関数を作成しました。
typedef struct adjList
{
vp node;
struct adjList *next;
}
adjList;
void createList (adjList *list, vp graph, int *place) /* place stores an index in an array of adjacency lists */
{
int i, temp = *place;
adjList *ptr;
if (graph)
{
list[temp].node = graph;
list[temp].next = NULL;
if (EDGE (graph))
{
ptr = list[temp].next;
for (i = 0; EDGE (graph)[i]; ++i)
{
ptr = malloc (sizeof (adjList));
ptr->node = EDGE (graph)[i];
ptr = ptr->next;
}
}
++(*place);
list = realloc (list, sizeof (adjList) * (*place + 1));
for (i = 0; EDGE (graph)[i]; ++i)
{
createList (list, EDGE (graph)[i], place);
}
}
}
このメインを使用すると、セグメンテーション違反が発生します。
int main()
{
int i;
int *temp = malloc (sizeof (int));
adjList *list, *ptr;
vp test;
*temp = 0; /* temp is an index starting from 0 */
test = malloc (sizeof (*test) + 4 * sizeof (vp));
list = malloc (sizeof (adjList));
LABEL (test) = malloc (sizeof (char));
LABEL (test)[0] = 'a';
for (i = 0; i < 3; ++i)
{
EDGE (test)[i] = malloc (sizeof (vertex));
}
LABEL (EDGE (test)[0]) = malloc (sizeof (char));
LABEL (EDGE (test)[0])[0] = 'b';
LABEL (EDGE (test)[1]) = malloc (sizeof (char));
LABEL (EDGE (test)[1])[0] = 'c';
LABEL (EDGE (test)[2]) = malloc (sizeof (char));
LABEL (EDGE (test)[2])[0] = 'd';
EDGE (EDGE (test)[0])[0] = NULL;
EDGE (EDGE (test)[1])[0] = NULL;
EDGE (EDGE (test)[2])[0] = NULL;
EDGE (test)[3] = NULL;
printf ("%d\n", sizeof (EDGE (test)) / sizeof (vp));
createList (list, test, temp);
list = realloc (list, sizeof (adjList) * (*temp));
printf ("%c\n", LABEL (test)[0]);
printf ("%d\n", (test == list[0].node));
for (ptr = list; ptr; ptr = ptr->next)
{
printf ("%c ", LABEL (ptr->node)[0]);
}
printf ("\n");
return 0;
}
デバッグ中に、隣接リストを作成する関数が「adjList」構造にポインターを格納することすらできないことがわかりました。メモリを適切に割り当てていない可能性があります。少しでも助けていただければ幸いです。
前もって感謝します。