为什么在尝试初始化数组时出错
Why I get error when I try to initialize an array?
我想初始化一个有n+1个元素的数组,并为第一个元素赋值,所以:
#include <iostream>
using namespace std;
double arry(int n,double s0);
int main()
{
arry(10,24.543);
return 0;
}
double arry(int n,double s0){
double s[n+1]={};
s[0]=s0;
for(int i=0;i<11;i++){
cout<<i<<"="<<s[i]<<endl;
}
}
这似乎是正确的,但当我运行它时,我在第13行收到了一条错误消息,如下所示:
错误:可能未初始化可变大小对象的
有人能修好吗?非常感谢。
double s[n+1]={};
C++中不允许使用s[n+1]
。您应该使用编译时常数。类似于s[10];
或
#define INDEX 10
double s[INDEX + 1]={};
使用此代码
#include <iostream>
#include <stdlib.h>
using namespace std;
void arry(int n,double s0);
int main()
{
arry(10,24.543);
}
void arry(int n,double s0){
double *s;
s = new double[n + 1];
s[0]=s0;
for(int i=0;i<11;i++){
cout<<i<<"="<<s[i]<<endl;
}
}
您必须使用malloc函数来动态分配内存
#include <iostream>
#include <stdlib.h>
using namespace std;
double arry(int n,double s0);
int main()
{
arry(10,24.543);
return 0;
}
double arry(int n,double s0){
double* s = (double*)malloc( sizeof(double) * (n + 1) ) ;
s[0]=s0;
for(int i=0;i<11;i++){
cout<<i<<"="<<s[i]<<endl;
}
}
相关文章:
- 使用 thread 类在 C++ 中构造线程的动态数组时出错
- 将链表转换为指针数组时出错
- 为 NewObjectA() 函数创建 jvalues 的参数数组时出错 - JNI Invocation API
- 基于数组的列表 - 动态数组创建时出错
- 从斐波那契序列 c++ 中的数组中查找正确的元素时出错
- 分段 使用 MPI_Gather 收集字符数组时出错
- 读取字符串字符时出错 - 对于数组中的字符串值
- 声明数组>> int arr[] 时出错;在C++(虽然在 Java 中有效)?
- 在 c++ 中返回一维数组时出错
- 将 2D 数组传递给 C++ 中的函数时出错
- 在 c++ 上创建动态数组时出错
- 尝试返回指向 Visual Studio 中的动态数组的指针时出错C++
- 将 find_if() 与数组一起使用的代码段中出错
- 在比较特定输入中的程序的数组中出错
- 分段 填充数组时出错
- 数组作为函数参数查找数组长度时出错
- C++:用户定义的类型数组出错
- C++中的数组出错
- 我正在创建精灵数组出错
- 在将代码从Windows移植到Linux时删除数组出错