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 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
|
#include <iostream>
#include <string>
using namespace std;
void getargs(int& height, int& width, int& length);
int ***initializearray(int& height, int& width, int& length, int*** carray);
void printarray(int& height, int& width, int& length, int*** carray);
bool goagain();
void freearray(int& height, int& width, int& length, int*** carray);
//Main function declares variables, then cycles
//through functions to get arguments from user,
//then set the carray pointer to the value
//the user specifies. Then print array.
//Next, use a while loops to determine if the
//user would like to resize the array.
//If so then repeat, otherwise free memory.
int main()
{
int height, width, length;
int ***carray;
do
{
getargs(height, width, length);
carray = initializearray(height, width, length, carray);
printarray(height, width, length, carray);
}
while(goagain());
freearray(height, width, length, carray);
}
//Function takes in arguments declared in main and
//sets them to a user defined value.
void getargs(int& height, int& width, int& length)
{
cout<<"Enter a height for your array:"<<endl;
cin>>height;
cout<<"Enter a width for your array:"<<endl;
cin>>width;
cout<<"Enter a length for your array:"<<endl;
cin>>length;
}
//Get values defined by user. Pass array into function.
//Allocate a 3 dimensional array and give it values.
//Delete the old array and pass the pointer to the new memory.
int ***initializearray(int& height, int& width, int& length, int*** carray)
{
int ***p_temparray = new int**[length];
for(int i=0;i<length;i++)
{
p_temparray[i] = new int*[width];
for(int j=0;j<width;j++)
{
p_temparray[i][j]=new int[height];
for(int x=0;x<height;x++)
{
p_temparray[i][j][x]=i*j*x;
}
}
}
delete [] carray;
return p_temparray;
}
//Get height width and length then print the values for each
//array coordinate.
void printarray(int& height, int& width, int& length, int*** carray)
{
for(int i=0;i<length;i++)
{
for(int j=0;j<width;j++)
{
for(int x=0;x<height;x++)
{
cout<<"carray["<<i<<"]["<<j<<"]["<<x<<"]="<<carray[i][j][x]<<endl;
}
}
}
}
//Check to see if user wants to resize array.
//If so, then loop functions again.
bool goagain()
{
string arg;
cout<<"Would you like to resize the array?\n";
cin>>arg;
if(arg=="y")
{
return true;
}
else
{
return false;
}
}
//Cycle through the array and delete allocated memory.
void freearray(int& height, int& width, int& length, int*** carray)
{
for(int i=0;i<length;i++)
{
delete [] carray[i];
for(int j=0;j<width;j++)
{
delete [] carray[i][j];
}
}
delete [] carray;
}
|