Doubling the Dynamic Array using pointers

I am having issues with the dynamic arrays. I am taking one array and creating a new one with double the size. I want to keep the original elements of the arrays and fill the remaining with -1. I am able to double the array but I cannot figure out how to fill the rest with -1 :(

Expected Result: 0 1 2 3 4 5 6 7 8 9 -1 -1 -1 -1 -1 -1 -1 -1 -1
What I am getting: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

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
int *resize (int *arr, int size)
{
  int *newArray;
  if (size <= 0)
  return NULL;

  newArray = new int [size*2];

 for (int i = 0; i < size*2; i++)

   if(i<size)
   {
     newArray[i] = arr[i];
   }

   else
  {
     newArray[i] = -1;
  }

   return newArray;
}

//This is in main

  int arrayOne [10] = {1,2,3,4,5,6,7,8,9,0};
  int *arrayPointer = resize(arrayOne, 10);

	for (int i=0; i<(10*2); i++)
	if (arrayOne[i] == arrayPointer[i])

  cout << i << " ";
  delete [] arrayPointer;

return 0;
}
do you need to use arrays?
can you use vectors?
yes only dynamic arrays and pointers
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
#include <iostream>
#include <algorithm>

int main()
{

   int old_size = 10;
   int new_size = 20;
   int* oldArr= new int[old_size];   
   int* newArr = new int[new_size];
   
   for (int i=0; i < old_size; i++)
   {
        oldArr[i] = i;   
   }
   
   std::copy(oldArr, oldArr + std::min(old_size, new_size), newArr);
   delete[] oldArr;   
   oldArr = newArr;
   
   for (int i=old_size; i < new_size; i++)
   {
        oldArr[i] = -1;   
   }
   
   for(int i=0; i < new_size; i++)
   {
       std::cout << oldArr[i] << " ";
   }
   
}
Last edited on
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
#include <iostream>

int main ()
{
  int old_size = 10;
  int new_size = old_size * 2;

  int* oldArr = new int[old_size];
  int* newArr = new int[new_size];

  // init old array
  for (int i = 0; i < old_size; i++)
  {
    oldArr[i] = i;
  }

  // init new Array
  for (int i = 0; i < new_size; i++)
  {
    newArr[i] = -1;
  }

  // copy from old array to new array
  for (int i = 0; i < old_size; i++)
  {
    newArr[i] = oldArr[i];
  }

  // display the new array
  for (int i = 0; i < new_size; i++)
  {
    std::cout << newArr[i] << " ";
  }
  std::cout << "\n\n";

  // clean up
  delete [] oldArr;
  delete [] newArr;

  system ("pause");
  return 0;
}
I feel like this kid is in my class lol
sorry I didn't get to say Thank You ... it helped

@WakeofMisery ... what class are you in and where ?
Topic archived. No new replies allowed.