How do I new and delete a 2D array in a function?

Hello all!
How do I new and delete a 2D array in a function?
My program:
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
#include <stdlib.h>
#include <iostream.h>

int **New2D(int m, int n);
void Free2D(int **ptr, int m);

int main(){
	int am, an;
	int **A;

	am=3,an=3;

	A = New2D(am, an);

	int i,j;
	for(i=0; i<3; i++)
		for(j=0; j<3; j++)
			cin>>*(*(A+am)+an);

	Free2D(A, am);

	system("pause"); 
	return 0;
}

void Free2D(int **ptr, int m){
	int i;
	for(i=0;i<m;i++) delete [] ptr[i];
	
	delete [] ptr;
}

int **New2D(int m, int n){
	int **ptr = new int*[m];

	int i;
	for(i=0;i<m;i++) ptr[i] = new int[n];

	return ptr;
}
Last edited on
closed account (zb0S216C)
1
2
3
4
5
6
7
8
9
10
11
12
13
// Allocation:
int **block(new int*[3U]);

if(block)
    for(unsigned short cycle(0U); cycle < 3U; ++cycle)
        block[cycle] = new int[5U];

// Deletion
if(block)
    for(unsigned short cycle(0U); cycle < 3U; ++cycle)
        delete [] block[cycle];

delete [] block;


The Elder Scrolls: Skyrim FTW

Wazzak
Last edited on
closed account (D80DSL3A)
Your code looks fine except for line 18 which should be: cin>>*(*(A+i)+j);

Here's another approach using a structure to automate allocation and deletion:
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
48
49
50
51
52
53
54
55
56
57
#include <iostream>
using namespace std;

struct arr2D
{
    int** ppInt;
    int m;
    int n;

    // constructor
    arr2D(int _m, int _n): ppInt(new int*[_m]), m(_m), n(_n)
    {
        for(int i=0; i<m; ++i)
            ppInt[i] = new int[n];
    }

    // destructor
    ~arr2D()
    {
        for(int i=0; i<m; ++i)
            delete [] ppInt[i];
        delete [] ppInt;
    }

    void get_values()
    {
        for(int i=0; i<m; ++i)
            for(int j=0; j<n; ++j)
            {
                cout << "arr[" << m << "][" << n << "] = ";
                cin >> ppInt[i][j];
            }
    }
    void print()
    {
        for(int i=0; i<m; ++i)
        {
            for(int j=0; j<n; ++j)
                cout << ppInt[i][j] << " ";
            cout << endl;
        }
    }

};

int main()
{  
    arr2D A(3,3);// allocation occurs here
    
    A.get_values();// initialization - get values from user
    A.print();// display elements

    // deletion is handled automatically by the destructor

    cout << endl;
    return 0;
}

EDIT: Corrected error in destructor
Last edited on
Thank for your replies,Framework and fun2code!!!

Last edited on
Topic archived. No new replies allowed.