我是一个新的c++,切换从matlab运行模拟更快。
我想初始化一个数组,并让它填充零。
# include <iostream>
# include <string>
# include <cmath>
using namespace std;
int main()
{
int nSteps = 10000;
int nReal = 10;
double H[nSteps*nReal];
return 0;
}它会产生一个错误:
expected constant expression
cannot allocate an array of constant size 0
'H' : unknown size你怎么做这件简单的事?有像matlab这样的命令库吗?
zeros(n);发布于 2015-09-24 07:42:39
带有单一均衡器的基于堆栈的数组直到结束时都是零填充的,但是您需要使数组边界等于const。
#include <iostream>
int main()
{
const int nSteps = 10;
const int nReal = 1;
const int N = nSteps * nReal;
double H[N] = { 0.0 };
for (int i = 0; i < N; ++i)
std::cout << H[i];
}Live Example
对于动态分配的数组,最好使用std::vector,这也不需要编译时已知的界限。
#include <iostream>
#include <vector>
int main()
{
int nSteps = 10;
int nReal = 1;
int N = nSteps * nReal;
std::vector<double> H(N);
for (int i = 0; i < N; ++i)
std::cout << H[i];
}Live Example。
或者(但不推荐),您可以manually allocate一个零填充数组,如
double* H = new double[nSteps*nReal](); // without the () there is no zero-initialization发布于 2015-09-24 07:47:40
如果你事先知道长度,你就可以
#define nSteps 10000
#define nReal 10然后
double H[nSteps*nReal] = {0};或者,也可以将const关键字添加到您的大小中,而不是使用define的关键字。
https://stackoverflow.com/questions/32755672
复制相似问题