2D dynamic array of pointers

Hello,

Could anyone pls explain to me how to create a dynamic two dimensional array of pointers. I searched the google, but I did not find anything useful that could help me solve the problem.

I tried to create the 2D array of pointers in the folowing way:

struct cluster_node
{
int vertex;
cluster_node *next;
};
cluster_node **cluster;

Afterwards I tried to allocate memory for rows and colomns:

cluster = NULL;
cg_edge_weight = new node * [20]; //allocate memory for rows

cluster[0] = new cluster_node[num_of_vertices+1]; //allocate memory for 0th row

Now if I try to assign the value NULL to cluster[0][0] (cluster[0][0] =NULL), I get a compiling error.


I would be greateful for any suggestions. Thanx:)



If cluster is a cluster_node**, then
cluster[0] is a cluster_node*, and
cluster[0][0] is a cluster_node.

What I would like to do here is to create a 2D hash table of linked lists. However, this synthacs does not seem to be working:(
I think that for the second dimension you are mixing arrays and linked lists.

Your cluster_node struct has a next pointer, implying that you want to make a linked list of cluster_nodes.

But you also want to make a hash table, presumably resolving conflicts by chaining, hence the linked list.

So I think all you want is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
struct cluster_node {
   // Best to provide a default constructor:
   cluster_node() : vertex(), next() {}

   // Make life easier (this is used to insert at front; may not be what you want)
   cluster_node( int value, cluster_node* next ) :
       vertex( value ), next( next ) {}

   int vertex;
   cluster_node* next;
};

cluster_node** hash_table = new cluster_node*[20];  // make hash table containing 20 rows

// null out the pointers
for( size_t i = 0; i < 20; ++i )
    hash_table[ i ] = 0; /* NULL */

// Insert one element:
hash_table[ 4 ] = new cluster_node( 3, hash_table[ 4 ] );  // Inserts at front; may not be what you want 
Thanks jsmith for your quick reply:)

You are really helping a lot
. However, I'm not mixing arrays and linked lists. I just wanted to make an array of hash table-linked lists. Therefore, in this example, I wanted to allocate memory for 20 hash tables of linked list.

Ex
cluster_node cluster = new cluster_node * [20];

I hope that this time, I succeded to point where the problem is.

Thank u once again, Una
The statement cluster[0][0] has dereferenced all your pointers.

So you have to assign an object of type cluster_node. A NULL is not the right type.


This should work:
1
2
3
cluster_node n;

cluster[0][0] = n;


Thanx Galik for your reply. I already tried to assign a node of type cluster_node, but it results in a compiling error.

erreur: no match for ‘operator=’ in ‘*((*((GBP*)this)->GBP::cluster) + ((unsigned int)(((unsigned int)i) * 8u))) = n’
operator = needs to be overloaded for cluster_node.
Topic archived. No new replies allowed.