3

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);
Jarod42
  • 203,559
  • 14
  • 181
  • 302
jarhead
  • 1,821
  • 4
  • 26
  • 46

2 Answers2

4

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
Community
  • 1
  • 1
TemplateRex
  • 69,038
  • 19
  • 164
  • 304
  • thanks using the vector library helped me with both issus, very helpful for my kind of programming! – jarhead Sep 24 '15 at 07:59
  • Note that you don't need to use an enum pre-C++11. You can just use `const`. (and since I don't think VS2010 has `constexpr`, `const` is probably what he would use) – Benjamin Lindley Sep 24 '15 at 08:02
  • @BenjaminLindley thanks, updated. I am so used to using `constexpr` nowadays that I didn't realise this. It's only for non-type template parameters that you can't always use `const` variables (depending on linkage etc.), and could need `constexpr`. – TemplateRex Sep 24 '15 at 10:18
2

If you know length in advance you can just do

#define nSteps 10000
#define nReal 10

Then

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

Or alternatively you can as well add const keyword to your sizes instead of using defines.

Giorgi Moniava
  • 27,046
  • 9
  • 53
  • 90