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.
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 = newint**;
s = t;
*s = newint*;
**s = newint*[j];
u = newint*;
u = v;
*u = newint[p];
*s = newint[p];
for (int e = 0; e <= j; e++)
{
*(s + e) = newint[p];
}
return 0;
}
-Can someone help me figure out ow to initialize each ROW of the program.
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 = newint* [n_rows];
for (int i = 0; i < n_rows; ++i) *(s + i) = newint[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!