Search code examples
c++arraysdynamic-arrays

C++ copying chars from static to dynamic array adds a bunch of random elements


I have an static array, but when copying values over to a dynamic array, I get a bunch of nonsense padded on. I need for the resulting dynamic array to be exactly 8 characters

unsigned char cipherText[9]; //Null terminated
cout<<cipherText<<endl;      //outputs = F,ÿi~█ó¡

unsigned char* bytes = new unsigned char[8];  //new dynamic array

//Loop copys each element from static to dynamic array.
for(int x = 0; x < 8; x++)
{       
    bytes[x] = cipherText[x];
}

cout<<bytes;     //output: F,ÿi~█ó¡²²²²½½½½½½½½ε■ε■

Solution

  • You need to update your code to copy the null terminator:

    unsigned char* bytes = new unsigned char[9];  //new dynamic array
    
    //Loop copys each element from static to dynamic array.
    for(int x = 0; x < 9; x++)
    {       
        bytes[x] = cipherText[x];
    }
    
    cout<<bytes;
    

    This is assuming that cipherText does in fact contain a null terminated string.