Pointer in array problem

Hello guys! I am new here and joined recently to show my simple problem because I am having final exam this week.
My problem is whenever I introduce pointers in this array code, a error shows up and I am having trouble understanding this error.

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
#include <iostream>

using namespace std;

int arror(int *arrr[],int *size){
int m=0, sum=0;
double average =0;

while(m<*size){
    cout << "ENTER data no." << m+1 << ": ";
    cin >> arrr[m];
    sum+= arrr[m];
    m++;
}
average = sum/ *size;
return average;
}

int main()
{   int n,arr[1000];
    cout << "How many data you want to check for this program accuracy? ";
    cin >> n;
    cout << "Okay it seems that their average is: " << arror(&arr,&n) << endl;
    return 0;
}
You can just pass an array, to a function, and make the function accept an int pointer.
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>

void get_input(int n, int *arr);
double average(int n, const int *arr);
using namespace std;

int main()
{   int n,arr[1000];
  cout << "How many data you want to check for this program accuracy? ";
  cin >> n;

  get_input(n, arr);
  cout << "Okay it seems that their average is: " <<   average(n, arr) << endl;
  return 0;
}
double average(int n, const int *arr) {
  double sum = 0;

  for (int i = 0; i < n; ++i) {
    sum += arr[i];
  }

  double average = sum/n;
  return average;
}
void get_input(int n,  int *arr) {
  for (int i = 0; i <n; ++i) {
    cout << "ENTER data no." << i+1 << ": ";
    cin >> arr[i];
  }
}
Last edited on
Oh thanks for the great help! That solution was top-notch!
arr[1000]
there is no need to declare additional memory if you're not going to use it. in this problem you can create the array on the heap so that you allocate just the memory you need:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>

double average( int* arr, const int& n)
{
    arr = new int[n];
    double sum{};

    for (size_t i = 0; i < n; ++i)
    {
        std::cout << "Enter the number \n";
        std::cin >> *(arr+i);
        sum += *(arr + i);
    }
    delete [] arr;//now you can delete the array
    return sum/n;
}

int main()
{
    int* p{};
    std::cout << average(p, 3);
}
Last edited on
Topic archived. No new replies allowed.