Allocation function

Hello y'all. I need help with a function.
I am asked to write a function that allocates memory and store data in an array of integer. I have to use base offset notation and the "new" operator. This is what i have so far.

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
int alloc()
{
	int j = 0, p = 0;
	int ***s, ***t, **u, **v;


	cout << "How Many Rows Should The Array Have ? (At least 2) --> ";
	cin >> j;

	cout << "How many columns should the array have ? (At least 2) --> ";
	cin >> p;

	s = new int**;
	s = t;

	*s = new int*;
	**s = new int*[j];


	u = new int*;
	u = v;
	*u = new int[p];

	*s = new int[p];

	for (int e = 0; e <= j; e++)
	{
			*(s + e) = new int[p];
	}


	return 0;
}  


-Can someone help me figure out ow to initialize each ROW of the program.
Last edited on
If you want a two-dimensional dynamic array you only need a single double pointer.

In fact, it is often (but not always) better to use a single array with m*n elements instead for performance reasons (because of cache locality). But that's besides the point.

1
2
int** s = new int* [n_rows]; 
for (int i = 0; i < n_rows; ++i) *(s + i) = new int[n_cols];


Then deletion is performed in reverse order:
1
2
for (int i = 0; i < n_rows; ++i) delete[] *(s + i);
delete[] s;


Do not forget to write delete[] instead of delete!
Topic archived. No new replies allowed.