I am trying to pass an DMA array and its size as an argument but it is giving an error

Viewed 164

I am trying to pass a dynamic memory allocated array and its size to a function 'sum' but it is giving error of permissive what should I do?

 #include<conio.h>
    #include<iostream>
    using namespace std;
     int sum(int n[], int *m)
      {
       for(int z=0;z<*m;z++)
      {
        cout<<"\n the output is = "<<n[z]<<"\n";
      }
       }

     int main()
        {

     int *n,*m,a; //declaration is done here**strong text**
     cout<<"enter the size of array = ";
      m=new int;             
      cin>>*m;
      n=new int[*m];
      for(int i=0;i<*m;i++)
       {
          cout<<"\n enter the "<<i+1<<" array = ";
          cin>>n[i];
                cout<<"\n";
        }
         /* for(int z=0;z<*m;z++)
       {
          cout<<"\n the output is = "<<n[z]<<"\n";
        }*/
      int sum(n,&m);//here "m" is an pointer and I am trying to pass int in a function with an array 
      return 0;
      }
1 Answers

Your code should, probably, look like the following (Linux Ubuntu + gcc):

#include <iostream>

using namespace std;

int sum(int n[], int m)
{
  int s=0;
  for(int z=0; z<m; z++)
  {
    cout<<"\n array["<<z<<"]= "<<n[z]<<"\n";
    s+=n[z];
   }
   return s;
}

int main()
{
  int *n,m;
  cout<<"enter the size of array = ";             
  cin>>m;
  n=new int[m];
  for(int i=0; i<m; i++)
  {
    cout<<"\n enter array["<<i+1<<"] value = ";
    cin>>n[i];
    cout<<"\n";
  }
  int s = sum(n, m);
  cout<<"s="<<s<<endl;
  return 0;
}

There is no use allocating the size of the array m dynamically. It is an ordinary int variable and can be initialized as

cin>>m;

You may also write the sum prototype in the form

int sum(int * n, int m)

It is another way of passing a 1-dimensional array as a function parameter.

Speaking frankly, these questions are the very basics of the language. You should, probably, read something like Dynamic memory allocation/dynamic arrays about dynamic memory allocation and dynamic arrays and Simple cases of std::cin usage about the simplest cases of std::cin usage in C++.

Related