copy static array in a dynamic array in c++

35 Views Asked by At

The main goal of this code is to copy part of the strings from myArray to neuArray and then output the copied strings from neuArray to the console. the code is working but not 100% because i get the following report: Access violation while reading at position 0xFFFFFFFFFFFF.

could someone maybe help? thanks in advance

string myArray[5];

const int len = (sizeof(myArray) / sizeof(myArray[0]));

myArray[0] = ausgabe; // die ausgabe ist ein binäre string 0101

const int x = 5;
const int y = 1;



string neuArray[x + y] = {};

memcpy(neuArray, myArray, len * (sizeof(string)));

for (int i = 0; i < x + y; i++) {
    cout << neuArray[i] <<endl;}
1

There are 1 best solutions below

2
Some programmer dude On

The problem with the code you show is that you use the C function memcpy. It will make a shallow byte-wise copy, which doesn't invoke the objects copy-semantics as expected by C++.

That means you will have undefined behavior when you try to access the "copied" objects.

You should use std::copy instead:

std::copy(std::begin(myArray), std::end(myArray), std::begin(neuArray));

Or stop using fixed-size arrays when you clearly need a dynamic array, and therefore should use std::vector instead.