here is my code and im not allowed to use a loop in the subarray function im pretty confused maybe someone can point me in the right direction i feel like im almost there..
int *duplicateArray(int *arr, int size)
{
int *newArray;
if (size<=0)
return NULL;
newArray = new int[size];
for (int index=0;index<size;index++)
newArray[index]=arr[index];
return newArray;
}
int* subArray(int *sub, int start, int length)
{
int aa[10]={1,2,3,4,5,6,7,8,9,10};
int *dup;
dup = aa;
duplicateArray(dup,10);
return dup;
}
int main()
{ cout << "Testing subArray: " << endl
<< "Expected result: 5, 6, 7, 8 " << endl;
int *subArr;
int start = 5;
subArr = subArray(subArr, 5,4);
for (int index = start; index<10; index++)
cout << subArr[index];
delete [] subArr;
subArr = 0;
So, since this is homework, I’m going to avoid posting a solution directly. You say that;
Yet, currently,
subArraycallsduplicateArray, which uses a loop. This seems to be in conflict with the spirit of the requirement.Since you haven’t said otherwise, I’m assuming that
subArrayshould duplicate the contents of its argument betweenstartand the end. So, what do we know?We know that the size of the returned array should be
length - startelements. We also know (well, perhaps) that a function namedmemcpyexists which allows you to copy a block of bytes from one place to another (assuming they do not overlap).(note that I am suggesting
memcpyhere because we are dealing with POD types (Plain Old Data) and because I doubt your class has delved into the STL. In the future you will be better served by something likestd::copy(), but for now this is ok)So, in order, we need to:
Declare a new array to return with
length - startelements. You must dynamically allocate this array! Currently you are returning a pointer to a locally declared array. That pointer becomes invalid as soon as the function returns.Copy
length - startelements (elements, not bytes! Make sure to take into account the number of elements as well as the size of an individual element) fromsub + startinto this new array.Return the new array (pointer really).
If I have somehow violated the requirements or intent of your assignment then you need to elaborate on your problem for me. Currently there is not much to go on.