为什么在尝试初始化数组时出错

Why I get error when I try to initialize an array?

本文关键字:数组 出错 初始化 为什么      更新时间:2023-10-16

我想初始化一个有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;
    }
}