gpt4 book ai didi

c++ - 我正在尝试将 DMA 数组及其大小作为参数传递,但它给出了一个错误

转载 作者:行者123 更新时间:2023-12-01 14:57:37 25 4
gpt4 key购买 nike

我正在尝试将动态内存分配数组及其大小传递给函数“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;
}

最佳答案

您的代码可能应该如下所示(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 的大小是没有用的。它是一个普通的int变量,可以初始化为

cin>>m;

您也可以将sum 原型(prototype)写成以下形式

int sum(int * n, int m)

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

坦率地说,这些问题是这门语言的基础知识。您可能应该阅读类似的内容 Dynamic memory allocation/dynamic arrays关于动态内存分配和动态数组以及 Simple cases of std::cin usage关于 C++ 中 std::cin 用法的最简单情况。

关于c++ - 我正在尝试将 DMA 数组及其大小作为参数传递,但它给出了一个错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62060979/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com