mibacode
mibacode

Reputation: 404

How to dynamically create an array of pointers?

I am trying to dynamically create an array of size 'n' that can contain pointers to multiple adjacency lists. However when I run my code, it doesn't result in an array of nodes, it just results in this:

Netbeans debugging variables

It's not an array, it's just a single node.

Here's my code:

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
};

Where am I going wrong?

Upvotes: 2

Views: 186

Answers (1)

Caesar
Caesar

Reputation: 9863

The issue is that there is no way to tell how large a piece of memory when you only have a pointer to the start of the memory and so your IDE just assumes that it is size is sizeof(datatype) and only shows you the first element.

Upvotes: 1

Related Questions