declaring a 2d array using pointers?

I am trying to declare a 2d array using pointers as it needs dynamic memory allocation. I know for link list implementation I can use "Node **myArray" where the two asterix declare its an array of pointers.
I am setting up a simple integer 2d array for a matrix.

Any help would be appreciated
This should work ..right?

 
    int **adj; // pointer to array of arrays (i.e 2d array) 


It is initialised later, as V is unknown, in the file using the following code.

1
2
3
4
5
6
7
8
9

    adj = new int*[V+1];            //adjacency matrix.


    // initially set all values to zero '0'
    for(v=1; v<=V; ++v) 
    {
        adj[v] = new int[v];
     }
yes (except that if an array has V elements, they are adj[0] to adj[V-1] ),
but see http://www.cplusplus.com/forum/articles/17108/
also, every row has a different length and you don't set them to 0.
Last edited on
Sorry that's my fault. Chopped up the code but never moved the comments.

1
2
3
4
5
6
7
    for(v=0; v<=V; ++v) 
    {
        for(u=0; u<=V; ++u) 
        {
        adj[v][u]=0 ;
        }   
    }


Thanks for the link.. really helpful
this is how to create 2D array where 2-nd dimenzions are diferent-> choosen by user:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
using namespace std;

int main () {
	short **twoDArray;
	short i, rows, columns;

	cout << "enter how many rows: ";
	cin >> rows;
	twoDArray = new short* [rows];

	for (i = 0; i < rows; i++) {
		cout << "how many columns in THIS --> [" << (i + 1) << "] ROW";
		cin >> columns;  // how many columns for each row!
		twoDArray [i] = new short [columns + 1];
		twoDArray [i] [0] = columns;

		for (short j = 1; j <= columns; j++)
			twoDArray [i] [j] = 0;
	}
	cout << "output of members: " << endl;
	for (i = 0; i < rows; i++)
		for (short j = 0; j <= twoDArray [i] [0]; j++)
			cout << "[" << i << "][" << j << "] = " << twoDArray [i] [j] << endl;

	for (i = 0; i < rows; i++)
		delete [] twoDArray [i];
	delete [] twoDArray;

	system ("pause");
	return 0;
}
Topic archived. No new replies allowed.