passing array to a function by pointer and reference

I have writen the following code to pass the array by pointer but there is one error if the error is removed probably it would be easier to do it by reference
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
 #include <iostream>
#include<conio.h>

using namespace std;
int pass(int *b[],const int n)
{
    int  sum;
    for(int i=0; i<n;i++)
    {
        sum+=b[i];
    }
    return sum;

}
int main ()
{
    
  const int num=5;
 int arr[num]={1,2,3,4};
 int res=pass(&arr,num);
 cout<<res<<endl;
 getch();
}
Error is here:
int pass(int *b[],const int n)

Either you pass the array by value as int b[] or as a pointer as int *b.

You can't create or pass an array of references.
By changing the reqiured code into a int *b. there is error in line 20.
You can't create or pass an array of references.

Why cant we can do it for all datatypes will you please elaborate.
If so isn't this passed by pointer and should be possible
int res=pass(&arr,num);

This must be:

int res=pass(arr,num);

Since the array name arr is a pointer to the first element of the array.
Last edited on
Thank you it works now :)
Topic archived. No new replies allowed.