Search code examples
c++arrayspaddingvariable-length-array

Initializing array in cpp and padding with zeros


I'm new a c++, switched from matlab to run simulations faster.
I want to initialize an array and have it padded 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;
}

It produces an error:

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

How do you do this simple thing? Is there a library with a command such as in matlab:

zeros(n);

Solution

  • Stack-based arrays with a single intializer are zero-filled until their end, but you need to make the array bounds equal to be 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, you best use std::vector, which also does not require compile-time known bounds

    #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 zero-filled array like

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