2-Dimensional array allocation
Nov 18, 2015 at 7:47am UTC
Hello,
I am trying to create 2D array allocation and assign values for them then delete them after printing them out on screen, i did everything right except this part i cant figure out what i should put in:
foo(int x[][2], int length1, int length2)
and the definition of the array in the main:
here is the full code so far, and i am not sure how to delete 2D array, can someone help me with that too, thanks
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
#include <iostream>
using namespace std;
void foo(int x[][2], int length1, int length2)
{
int ** pvalue = new int *[length1];
for (int i = 0; i < length1; i++)
{
pvalue[i] = new int [length2];
}
for (int i = 0; i < length1; i++)
{
for (int j = 0; j < length2; j++)
{
pvalue[i][j] = i*j;
x[i][j] = pvalue[i][j];
}
}
}
int main()
{
int s1, s2;
int x[2][2];
cout << "Please enter the value of size 1: " ; cin >> s1; cout << endl << "Please enter the value of size 2: " ; cin >> s2;
foo(x, s1, s2);
for (int i = 0; i < s1; i++)
{
for (int j = 0; j < s2; j++)
{
cout << "i = " << i << " j = " << j << " y[i][j] = " << x[i][j] << endl;
}
}
system("PAUSE" );
return 0;
}
Nov 18, 2015 at 8:56am UTC
delete
is like
new
just reverse:
1 2 3 4 5
for (int i = 0; i < length1; i++)
{
delete [] pvalue[i];
}
delete [] pvalue;
Nov 18, 2015 at 9:55am UTC
Thanks,
what about the function foo?
is it correct how i defined the parameters ?
and how about the array x in main function ?
Nov 18, 2015 at 3:22pm UTC
what about the function foo?
if length1/length2 > 2 the program will crash due to an out of bounds operation.
is it correct how i defined the parameters ?
Yes.
and how about the array x in main function ?
Well,
x
determines the maximum value of s1/s2. Thus the dynamically created array has no avail.
Nov 19, 2015 at 2:21am UTC
Thank you so much
Topic archived. No new replies allowed.