在c ++中列出struct里面的内容

时间:2016-09-11 19:00:40

标签: c++

我在c ++中的结构中有一个列表;我只是想像往常一样在这个列表中插入元素。

我的结构是:

// A structure to represent an adjacency list node
struct AdjListNode
{
    int dest;
    int weight;
    std::list<int> adjacents;
    struct AdjListNode* next;
};

// A structure to represent an adjacency list
struct AdjList
{
    int pos;
    struct AdjListNode *head; // pointer to head node of list
};

// A structure to represent a graph. A graph is an array of adjacency lists.
// Size of array will be V (number of vertices in graph)
struct Graph
{
    int V;
    struct AdjList* array;
};

struct Graph* createGraph(int V)
{
    struct Graph* graph = (struct Graph*) malloc(sizeof(struct Graph));
    graph->V = V;

    // Create an array of adjacency lists. Size of array will be V
    graph->array = (struct AdjList*) malloc(V * sizeof(struct AdjList));


    // Initialize each adjacency list as empty by making head as NULL
    for (int i = 0; i < V; ++i) {
        graph->array[i].head = NULL;
    }

    return graph;
}

当我尝试aceess时:

graph->array[position].head->adjacents->push_back(number);

它只是向我提示:

处理以退出代码139结束(由信号11:SIGSEGV中断)

抱歉,我对此错误一无所知。

1 个答案:

答案 0 :(得分:1)

分段错误来自

graph->array[position].head->adjacents.push_back(number);

graph->array[position].head = NULL;

我认为你的代码中有隐式struct不变量,因为你有两个可能连接的列表:链接列表从AdjList::head开始并迭代AdjNode::next和列表{{1 }}

要保持连接,您可以添加一个(C样式)函数,在两个列表中添加元素。

AdjNode::adjacent

请注意,将C样式(malloc / free)与C ++样式(特别是标准模板库的容器)混合使用是个坏主意。我的代码的注释部分会创建一个分段错误,因为void addAdjacent(AdjList& list, int adjacent) { // struct AdjListNode* newNode = (struct AdjListNode*) malloc(sizeof(struct AdjListNode)); struct AdjListNode* newNode = new AdjListNode; newNode->next = list.head; list.head = newNode; newNode->dest = 0; newNode->weight = 0; newNode->adjacents = std::list<int>(); // undefined behavior with malloc newNode->adjacents.push_back(adjacent); } 的字段没有填充0。

最后,即使有很多内存泄漏,以下std::list函数也能正常工作(参见valgrind工具)

main

C ++ - 98解决方案(没有任何内存泄漏)可能是:

int main(int argc, char** argv) {
   struct Graph* graph = createGraph(2);
   addAdjacent(graph->array[0], 1);
   addAdjacent(graph->array[1], 2);
   free(graph);
   return 0;
}