duplicating dynamic arrays

I need quick help with the output of my code when I try and duplicate my dynamic array. I'd rather just show instead of tell and give my current code.

Here's what I want:
Enter in size of array
3
Enter number:3
Enter number:6
Enter number:7
Following array is:3 6 7
Duplicate is: 3 6 7

Here's what I get:
Enter in array size
3
Input numbers:3
following array is:3
Here's your duplicate:3
Input numbers:6
following array is:6
Here's your duplicate:6
Input numbers:7
following array is:7
Here's your duplicate:7



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>
using namespace std;
int* duplicate(int* arr, int& size,int*dup);
int main()
{
	int* arr;
	int* dup;
	int size;
	cout << "Enter in size of array" << endl;
	cin >> size;
	arr = new int[size];
	dup = new int[size];
	arr = duplicate(arr, size,dup);
	for (int i = 0;i < size;i++)
	{
		cout << "Input numbers: ";
		cin >> arr[i];
		cout << "Following array is: " << " " << arr[i] << endl;
		cout << "Here's the duplicate: " << " " << dup[i] << endl;
	}
	return 0;
}

int* duplicate(int* arr, int& size,int*dup)
{
	for (int i = 0;i < size;i++)
	{
		dup[i] = arr[i];
	}
	return dup;
}


I know I'm on the right track, but need some guidance.
> cout << "Input numbers: ";
This in a for loop of it's own.

> cout << "Following array is: " << " " << arr[i] << endl;
This in another for loop, after you've finished inputting data.

> cout << "Here's the duplicate: " << " " << dup[i] << endl;
This in yet another for loop, after you've called duplicate.
If you can use std::vector instead of old style dynamic arrays. Less problems and easier to deal with.
Duplicate std::vector is one line code

1
2
std::vector<int> arr;
std::vector<int> dup = arr;


It's up on the student to tell his teacher to teach the right way ;)
Last edited on
its one line the old way, too, if you use memcpy (and the type of data being move is simple)
its not the number of lines that is the problem.

depending on what you want, you can also make dup = arr pointer-wise. Not a true copy, but sometimes, this is all you need to do.
Last edited on
You forget the line of code which allocates memory, the line of code which hopefully delete the memory. The extra variables for the allocated size and the used size. And of course more lines of code for the manual memory management.

More line of codes are more failures are more death people on the road with auto cars :/
Topic archived. No new replies allowed.