Initialize an already declared char array in C ++

I want to use something like this:

char theArray[]=new char[8];
theArray= { 1,2,3,4,5,6,7,8};

instead

char theArray[] = { 1,2,3,4,5,6,7,8};

Is this possible?

+3
source share
6 answers

C ++ 0x

char* ch;
ch = new char[8]{1, 2, 3, 4, 5, 6, 7, 8};

@David Thornley: then switch these lines and there is no problem. And seriously, you are talking about redistribution char[8]in the same memory pool as the previous value, then you need to play with your own allocators, something like:

char* ch1 = new char[8]{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'i'};
char* ch2 = new(ch1) char[8]{1, 2, 3, 4, 5, 6, 7, 8};

afaik OP is unlikely to be needed.

+6
source
char theArrayCopy[] = { 1,2,3,4,5,6,7,8}; 
//
//
char* theArray=new char[sizeof(theArrayCopy)]; 
// or
char theArray[sizeof(theArrayCopy)]; 

memcpy(theArray, theArrayCopy, sizeof(theArrayCopy));
+4
source

, , , , - Boost Assign, - :

std::vector<int> v;

v += 1, 2, 3, 4, 5, 6, 7, 8;

, , , - , . OTOH, - , , , .

+3

, , :

memcpy( theArray, "\x01\x02\x03\x04\x05\x06\x07\x08", sizeof(theArray) );
+2

. , , , , CW...

, ...

class IntegerSequenceGenerator
{
    int step_;
    int value_;
public:
    IntegerSequenceGenerator(int start = 0, int step = 1)
        : step_(step), value_(start) {}
    int operator()() {
        int result = value_ + step_;
        std::swap(result, value_);
        return result;
    }
};

:

int main() {
    std::vector<int> myArray;
    std::generate_n(std::back_inserter(myArray), 8, IntegerSequenceGenerator());
}

:

int main() {
    std::vector<int> myArray(8);
    std::generate(myArray.begin(), myArray.end(), IntegerSequenceGenerator());
}

int main() {
    int myArray[8];
    std::generate(myArray, myArray + (sizeof(myArray)/sizeof(int)), IntegerSequenceGenerator());
}
+1

, . ( .)

char[8] :

char theArray[] = { 1,2,3,4,5,6,7,8};

This puts it in a heap (this is actually illegal, but I assume your compiler accepts it):

char theArray[]=new char[8];

Suppose you really don't want this on the heap, but just want to initialize it, this will work:

char theArray[max_array_size]; // need to specify size to place on stack

/* code */

static const char theInitializer[] = { 1,2,3,4,5,6,7,8};
std::copy( theInitializer, theInitializer + sizeof theInitializer, theArray );
+1
source

Source: https://habr.com/ru/post/1766790/


All Articles