如何动态创建指针数组?

时间:2014-04-22 03:00:41

标签: c++ arrays pointers

我正在尝试动态创建一个大小为'n'的数组,该数组可以包含指向多个邻接列表的指针。但是,当我运行我的代码时,它不会产生一个节点数组,它只会导致:

Netbeans debugging variables

它不是一个数组,它只是一个节点。

这是我的代码:

的main.cpp

#include "graph.h"
using namespace std;

int main() {
    graph g;
    return 0;
}

graph.cpp

#include "graph.h"

// Constructor
graph::graph()
{
    int size = 5; // 
    // Allocate array of size (n) and fill each with null
    adjListArray = new node*[size];

    // Set each entry in array to NULL
    for (int i = 0; i < size; i++)
    {
        adjListArray[i] = NULL;
    }
}

graph.h

#include<cassert>
#include<iostream>
#include<string>
#include<fstream>
using namespace std;

struct node
{
    int name;
    node *next;
};

class graph
{
    public:
        // Constructors/destructors
        graph();
        ~graph();

    private:
        node** adjListArray; // Array of pointers to each adjacency list
};

我哪里错了?

1 个答案:

答案 0 :(得分:1)

问题是当你只有一个指向内存开头的指针时,无法判断一块内存有多大,因此你的IDE只假设它的大小是sizeof(datatype)并且只显示你是第一个元素。

相关问题