3-d array using alloc

I have written a subroutine that will create a 2-d array using alloc below:

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
using namespace std;

double** calloc_2d(long int l,long int m)	//allocate a double matrix
{
	double** a = (double**) calloc(l, sizeof(double*));
	
	long int i;
	
	for(i=0; i<l; i++)
	{
		a[i] = (double*) calloc(m, sizeof(double));
	}
	
	
	return a;
}

int main()
{

	int size_i = 10;		//number of ellements in 2-d array
	int size_j = 20;
	
	double** a;
	a = calloc_2d(size_i,size_j);	//a has been declared as a 2-d array and initialized as zero

	return 0;
}




I want to generalize this to a 3-d array, but I'm having problems. The code for the 3-d array compiles but when I run the code it never finishes running. It's like it is stuck in a infinite loop. This is what I have:

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <iostream>

using namespace std;

double*** calloc_2d(long int l,long int m, long int n)	//allocate a double matrix
{
	double*** a = (double***) calloc(l, sizeof(double**));
	
	for(long int i=0; i<l; i++)
	{
		a[i] = (double**) calloc(m, sizeof(double*));
		
		for(long int j=0; i<m; j++)
		{
			a[i][j] = (double*) calloc(n, sizeof(double));
		}
	}
	
	
	return a;
}

int main()
{

	int size_i = 5;		//number of ellements in 3-d array
	int size_j = 10;
	int size_k = 15;

	double*** a;
	a = calloc_2d(size_i,size_j,size_k);	//a has been declared as a 3-d array and initialized as zero
	
	for(int i=0; i<size_i; i++)
	{
		for(int j=0; j<size_j; j++)
		{
			for(int k=0; k<size_j; k++)
			{
				cout << "i = " << i << " j = " << j << " k = " << k << endl << a[i][j][k] << endl;
			}
		}
	}



	return 0;
}


Any suggestions would be much appreciated.
Just looking over it, it seems fine. Did you try running it through a debugger to see where it is getting stuck?
You might want to try a more manageable way to store a multi-dimensional array. You can use the formula a=z*width*height+y*width+x (correct me if I'm wrong) to encapsulate it in a class as a 1d array. Something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
template<typename T>
struct array3d{
    T* data;
    int w,l,h
    array3d(int width,int length,int height){
        data=new T[width*length*height];
        w=width;
        l=length;
        h=height;}
    ~array3d(){
        delete[] data;}
    T& operator()(int x,int y,int z){
        return data[z*width*height+y*width+x];}};

You can add a bunch of other functions to this, but this is the bare bones that you need to encapsulate 3d arrays.
Topic archived. No new replies allowed.