Arrays & Arguments

Hey guys, I'm really new to C++ and I need to write a function that accepts an int array and the array's size as arguments. I dont really even know where to begin! The function should create a new array that is one element larger than the argument array. Any help is appreciated because I've been working for a while and haven't gotten anywhere. Thank you!


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <iomanip>
using namespace std;

void print_array(int*,const int);

int main()
{

}




The function you have will take an array and it's size as arguments so you got that going for you.

If this is not a homework, if this is only for your own practice, then you should use std::vector instead of bothering to resize an array, there's no point to it.

However, if you insist on using an array, then I believe you're going to need to declare the array dynamically to be able to resize it - http://www.cplusplus.com/doc/tutorial/dynamic/

http://bfy.tw/4ONa
I actually found out what to do! Here is the solution for others if they run across the same problem.

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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <iostream>
#include <iomanip>
#include <ctime>
using namespace std;
int *duplicateArray(const int *, int);
void displayArray(int[], int);

int main()
{
	
	const int SIZE1 = 7;

	
	int array1 [SIZE1] = { 5, 10, 15, 20, 25, 30, 35};

	int *dup1;

	
	dup1 = duplicateArray(array1, SIZE1);


	cout << "Below is the original array:\n";
	displayArray(array1, SIZE1);

	
	cout << "\nBelow is the duplicate array:\n";
	displayArray(dup1, SIZE1);

	delete [] dup1;
	dup1 = 0;
	return 0;
}

int *duplicateArray(const int *arr, int size)
{
	int *newArray;

	// Validate the size. If 0 or negative number, pass a null.
	if (size <= 0)
		return NULL;

	
	newArray = new int[size + 1];
	
	newArray[0] = 0;

	
	for (int index = 0; index + 1 < size; index++)
		newArray[index + 1] = arr[index];
	
		
	
	return newArray;
}

void displayArray(int arr[], int size)
{
	for (int index = 0; index < size ; index++)
		cout << arr[index] << " ";
	cout <<endl;
}
Last edited on
Topic archived. No new replies allowed.