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
|
#include <iostream>
using namespace std;
//Function Prototypes:
void copyArray(int *&i_array,int *t_array,int i_size);
void changeArraySize(int *&i_array,int &i_size,int new_size);
void printArray(int *i_array,int i_size);
//The main function:
//No argument: Though you could easily do that...
int main()
{
//Stub data: assuming 5 data were taken already.
//---------------------Declarations and Initializations-----------------------------||
int i_size = 5;//our integer arrays size. Hard coded, but yours can be modified.
int *i_array= new int[5];//Our hard coded integer array (pointer to it that is)
int l_array[5] = {3,2,1,5,4};//Local array with values
//---------------------Actual Processing--------------------------------------------||
copyArray(i_array,l_array,i_size);//copying array!
printArray(i_array,i_size);//Printing before increment
changeArraySize(i_array,i_size,i_size+1);//incrementing
i_array[5] = 82;//Let us modify our new (supposedly empty slots) value:
printArray(i_array,i_size);//Printing after increment
//---------------------Clean Up-----------------------------------------------------||
delete []i_array;//We are done playing, let us free our memory at i_array.
return 0;
}
//Simple copy service:
//Argument#1 is the array to be kept,
//argument#2 is the copy array to be copied,
//argument#3 is the number of elements copied.
void copyArray(int *&i_array,int *t_array,int i_size)//First argument by reference
{
for(int i=0;i<i_size;i++)//Don't step out of bound(Less than max size)
{
i_array[i]=t_array[i];//Copy values : exactly like an array.
}
}
//Simple increment service:
//Argument#1 is the pointer to array by reference,
//argument#2 is the number of old elements,
//argument#3 is the number of new elements.
void changeArraySize(int *&i_array,int &i_size,int new_size)//First argument by reference
{
int *t_array = new int[new_size];//Create a new temporary array of new_size
copyArray(t_array,i_array,i_size+new_size-i_size);
//Math: Itself + the difference: (1,-1) or (0) if they're equal.
delete []i_array;//Now we can release the old memory: Farewell...
i_array = t_array;//Now we can copy/re-point: Re-assign pointer.
t_array = 0;//Not necessary, but good practice : deallocate pointing device, not delete.
i_size+=new_size-i_size;//Modify our logical size.
//Math: Itself + the difference (1,-1) or (0) if they're equal.
}
//Simple printing service:
//Argument#1 is the array,
//argument#2 is the size of the array.
void printArray(int *i_array,int i_size)
{
cout<<"===Printing==="<<endl;
for(int i=0;i<i_size;i++)//Don't step out of bound(Less than max size)
{
cout<<"At index["<<i<<"]: "<<i_array[i]<<endl;
}
cout<<"===Printing==="<<endl<<endl;
}
|