1

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;
Ed S.
  • 122,712
  • 22
  • 185
  • 265
David Salazar
  • 133
  • 1
  • 1
  • 8
  • Look at [this](http://stackoverflow.com/a/3902230/1387612) – janisz Oct 01 '12 at 19:08
  • I guess that in `subArray` you want to call `duplicateArray` passing `sub+start` to represent the first element of the array to be copied, and `length` as the array size. – Marius Bancila Oct 01 '12 at 20:12

1 Answers1

2

So, since this is homework, I'm going to avoid posting a solution directly. You say that;

im not allowed to use a loop in the subarray function

Yet, currently, subArray calls duplicateArray, 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 subArray should duplicate the contents of its argument between start and the end. So, what do we know?

We know that the size of the returned array should be length - start elements. We also know (well, perhaps) that a function named memcpy exists which allows you to copy a block of bytes from one place to another (assuming they do not overlap).

(note that I am suggesting memcpy here 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 like std::copy(), but for now this is ok)

So, in order, we need to:

  1. Declare a new array to return with length - start elements. 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.

  2. Copy length - start elements (elements, not bytes! Make sure to take into account the number of elements as well as the size of an individual element) from sub + start into this new array.

  3. 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.

Community
  • 1
  • 1
Ed S.
  • 122,712
  • 22
  • 185
  • 265