我试图传递一个DMA数组和它的大小作为一个参数,但它给出了一个错误信息

问题描述 投票:0回答:1

我试图将一个动态内存分配的数组和它的大小传递给一个函数 "sum",但它给出了允许的错误,我该怎么办?

 #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;
      }
c++ error-handling
1个回答
0
投票

你的代码可能应该像下面这样(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;
}

没有必要分配数组的大小。m 动态地。它是一个普通的 变量,可以初始化为

cin>>m;

你也可以写 金额 样机

int sum(int * n, int m)

这是传递一个一维数组作为函数参数的另一种方式。

说实话,这些问题都是语言的基础知识。你可能应该,读到这样的内容动态内存分配动态数组关于动态内存分配和动态数组以及std::cin使用的简单案例关于在C++中最简单的std::cin使用情况。

© www.soinside.com 2019 - 2024. All rights reserved.