Array Error

Pages: 12
so this is what I have now, i still have some errors but can i get feedback on it? i have some help from my teacher

@seeplus I do read the replies and I appreciate the help, I'm just a tad bit confused still and this is a little new to me, I apologize


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



int sortArray(int userArray, int arraySize);

int main()
{

	int arraySize = 0;

	cout << "\nThis program creates an array of various numbers and will sort them." << endl;

	cout << "\nHow large would you like the array? ";
	cin >> arraySize;

	int* userArray[] = { new int[arraySize] };

	//make user input values
	for (int i = 0; i < arraySize; i++)
	{
		cout << "Please input integer #" << i << ":		" << endl;
		cin >> userArray[i];
	}

	for (int i = 0; i < arraySize; i++)
	{
		cout << "userArray{" << i << "] = " << userArray[i];
	
	}

	delete[]userArray;

	cout << "The average is: " << sortArray[](userArray, arraySize) << endl;

}


int sortArray(int* userArray, int arraySize)
{
	
    int i;
    float avg, sum = 0;
    for(i = 0; i < arraySize; i++)
    {
        sum += userArray[i];
    }
    avg = sum/arraySize;
    return avg;
}

Last edited on
On line 18 remove the square brackets on the LHS ... you are defining a pointer.

On line 35 remove the square brackets after sortArray. You are returning a single numerical value, not an array.

You deleted your array on line 33 BEFORE YOU USED IT!

Line 40 (and line 6) - the return type of the function is float, not int.

sortArray seems a strange name to something that calculates an average.

If you really want to use new/delete (you shouldn't), then:

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

double avgArray(const int* userArray, size_t arraySize);

int main()
{
	size_t arraySize {};

	cout << "\nThis program creates an array of various numbers and will sort them.\n";
	cout << "\nHow large would you like the array? ";
	cin >> arraySize;

	const auto userArray {new int[arraySize] {}};

	//make user input values
	for (size_t i = 0; i < arraySize; ++i) {
		cout << "Please input integer #" << i << ": ";
		cin >> userArray[i];
	}

	for (size_t i = 0; i < arraySize; ++i)
		cout << "\nuserArray{" << i << "] = " << userArray[i];

	cout << "\n\nThe average is: " << avgArray(userArray, arraySize) << '\n';

	delete[] userArray;
}

double avgArray(const int* userArray, size_t arraySize)
{
	double sum {};

	for (size_t i = 0; i < arraySize; ++i)
		sum += userArray[i];

	return sum / arraySize;
}

Last edited on
Topic archived. No new replies allowed.
Pages: 12