Initializing an array in cpp and filling with zeros

I am new C ++, switched from matlab to run simulations faster.
I want to initialize an array and supply it with zeros.

    # include <iostream>
# include <string>
# include <cmath>
using namespace std;

int main()
{
    int nSteps = 10000;
    int nReal = 10;
    double H[nSteps*nReal];
    return 0;
}

      

An error message is displayed:

expected constant expression    
cannot allocate an array of constant size 0    
'H' : unknown size

      

How do you do it? There is a library with a command like in matlab:

zeros(n);

      

+3


source to share


2 answers


Stack-based arrays with a single invoker are zero-padded to the end, but you need to make the bounds of the array equal 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

For dynamically allocated arrays, it is best to use std::vector

which also does not require known compile time estimates



#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 .

Alternatively (but not recommended) you can manually allocate a null filled array, like

double* H = new double[nSteps*nReal](); // without the () there is no zero-initialization

      

+4


source


If you know the length in advance, you can simply do

#define nSteps 10000
#define nReal 10

      

Then



double H[nSteps*nReal] = {0};

      

Or, you can also add a keyword const

to your sizes instead of using define

s.

+2


source







All Articles