P
Patrick
Im having trouble with arrays
(1) I want to create an array myArray in "main".
(2) Then call a function from "main" which I pass myArray to.
(3) The function modifies the size and elements of myArray.
(4) When we return from the function, myArray now has a new size, and new elements.
Is this possible with arrays (i realise it can be easily achieved with vectors)
Here is some code below outlining the general structure.
Any help greatly appreciated,
Pat
#include <iostream>
#include <string>
#include <sstream>
string arrayToString(const int a[],const int length);
void function(int *array,int& arrayLength);
int main(int argc, char *argv[])
{ //int *array = new int[3];
//array[0]=0;array[1]=1;array[2]=2;
//i would prefer to declare the array this way initially
int array[] = {1,2,3};
int arrayLength = 3;
//print out the original elements of the array
cout << arrayToString(array, arrayLength) << "\n";
//i want to change the size and content of "array"
function(array,arrayLength);
//print out the new elements of the array
cout << arrayToString(array, arrayLength) << "\n";
return 0;
}
void function(int *array,int& arrayLength)
{ //change the size of array to length 2 say
arrayLength = 2;
//change the contents of the array
}
string arrayToString(const int a[],const int length)
{ ostringstream result;
result << "[";
for (int i=0;i<length-1;i++)
result << a << ", ";
result << a[length-1] << "]";
return result.str();
}
(1) I want to create an array myArray in "main".
(2) Then call a function from "main" which I pass myArray to.
(3) The function modifies the size and elements of myArray.
(4) When we return from the function, myArray now has a new size, and new elements.
Is this possible with arrays (i realise it can be easily achieved with vectors)
Here is some code below outlining the general structure.
Any help greatly appreciated,
Pat
#include <iostream>
#include <string>
#include <sstream>
string arrayToString(const int a[],const int length);
void function(int *array,int& arrayLength);
int main(int argc, char *argv[])
{ //int *array = new int[3];
//array[0]=0;array[1]=1;array[2]=2;
//i would prefer to declare the array this way initially
int array[] = {1,2,3};
int arrayLength = 3;
//print out the original elements of the array
cout << arrayToString(array, arrayLength) << "\n";
//i want to change the size and content of "array"
function(array,arrayLength);
//print out the new elements of the array
cout << arrayToString(array, arrayLength) << "\n";
return 0;
}
void function(int *array,int& arrayLength)
{ //change the size of array to length 2 say
arrayLength = 2;
//change the contents of the array
}
string arrayToString(const int a[],const int length)
{ ostringstream result;
result << "[";
for (int i=0;i<length-1;i++)
result << a << ", ";
result << a[length-1] << "]";
return result.str();
}