-3

In C I have

unsigned long arr[256]={0x00000000L,0x01020304L,0x21223212L,...}

in C++ in .h-file i have

private:
    unsigned long arr[256];

how-to populate it (fastest way) in .cpp file with 256 constant values?

arr[256]={...}
// and
arr={...}

not work :-\

askovpen
  • 2,438
  • 22
  • 37

4 Answers4

1

Use initializer list in constructor:

// .h
class C
{
public:
    C();
private:
    unsigned long arr[256];
};

// .cpp
C::C() : arr{0x00000000L, 0x01020304L, 0x21223212L, ...} {}

Note that std::array may be an alternative which has more intuitive syntax and is assignable.

Jarod42
  • 203,559
  • 14
  • 181
  • 302
0

If you insist on using plain arrays, just std::memcpy(&this->arr[0], &::initial_values_arr[0], sizeof (::initial_values_arr));

wilx
  • 17,697
  • 6
  • 59
  • 114
  • do you offer make in cpp local array `unsigned long arrtmp[256]={...}` and std::memcpy it to global arr[256]? maybe exists too easy solution? – askovpen Jan 03 '15 at 21:02
0

Why do you want to have an array of constants as a member variable?

If values are supposed to be changed, then you will need C++11, and you should be able to use it in a same way as in C - in-class initialization of non-static non-const member variables is now allowed (you may want to take a look at: C++11 allows in-class initialization of non-static and non-const members. What changed? ).

If you want to have an array of constants, you can still use C style (and array that is either global or local to a file), if you wish to. I'm not saying it's good style, but compilers accept it.

Community
  • 1
  • 1
Tomasz Lewowski
  • 1,935
  • 21
  • 29
0

This is standard C++ code:

class C
{
private:
    unsigned long arr[256] = {0x00000000L,0x01020304L,0x21223212L};
};

auto main() -> int
{
    C c; (void) c;
}

Unfortunately it doesn't compile with Visual C++ 19.00.22310.1. Workaround:

#include <array>

class C
{
private:
    std::array<unsigned long, 256> arr;

public:
    C(): arr( {0x00000000L,0x01020304L,0x21223212L} ) {}
};

auto main() -> int
{
    C c; (void) c;
}
Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331