Having trouble passing array by reference

In my code, the user enters an array to whichever size they want (max 100). I'm trying to create a function insert() that allows the user to insert a new element into the array. I'm having trouble with parameters even though I've looked it up so many times. My main issue is that my program says my argument for double arr[] is incompatible with the parameter type double on line 27. Am I passing by reference wrong?

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
#include <iostream>
using namespace std;

const int CAPACITY = 100;

void insert(double arr[], double num, int i, int size);
void sort(double arr[], int size);

int main()
{
	double num, arr[CAPACITY];
	int size, i = 0;

	cout << "How many numbers do you want to enter? (no more than 100) " << endl;
	cin >> size;
	cout << "Enter " << size << " numbers: " << endl;

	for (int i = 0; i < size; i++)
	{
		cin >> arr[i];
	}
	for (int i = 0; i < size; i++)
	{
		cout << arr[i] << "\t";
	}

	insert(arr[i], num, i, size);
}

void insert(double arr[], double num, int i, int size)
{
	int pos, newElement;
	cout << "Choose a number to insert: " << endl;
	cin >> newElement;

	cout << "Choose a position to insert into: " << endl;
	cin >> pos;

	for (i = size; i > pos; i--)
	{
		arr[i] = arr[i - 1];
	}
	arr[pos] = newElement;

	cout << "The new array is: " << endl;
	
	for (i = 0; i < size + 1; i++)
	{
		cout << arr[i] << "\t";
	}
}
Last edited on
See Any Comment below for a better description
Last edited on
do I only need an ampersand in line 27? Or for lines 6 and 30 also?
Hello alexa7707,

On line 27 the first argument is sending the function a single element of the array whereas the function is expecting the whole array not one element. Line 27 should be insert(arr, num, i, size);.

Line 37 is OK, but remember that arrays are zero based, so unless the user has a way to know the correct number to enter you will have to subtract one from pos before you continue. Next if "size" is the usable size of the array you will need to add one before the function ends. When the function receives "size" it would work better as a reference so that it is changed in main.

Note: Always good practice to initialize your variables when they are defined. The simplest way is int size{};. The empty {} will give it a value of zero.

Line 47 if you add one to size before here the "+ 1" will not be needed.

Hope that helps,

Andy
Topic archived. No new replies allowed.