1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
|
#include <iostream>
#include <string.h>
using namespace std;
class myClass
{
public :
myClass();
~myClass();
struct DynamicArray
{
uint8_t * data;
size_t size;
};
void addToArray( DynamicArray & array, uint8_t * data, size_t len );
DynamicArray myDynamicArray1;
DynamicArray myDynamicArray2;
};
myClass::myClass() :
myDynamicArray1( { nullptr, 0 } ),
myDynamicArray2( { nullptr, 0 } )
{
}
myClass::~myClass()
{
if ( myDynamicArray1.data != nullptr )
{
delete[] myDynamicArray1.data;
}
if ( myDynamicArray2.data != nullptr )
{
delete[] myDynamicArray2.data;
}
}
void myClass::addToArray( DynamicArray & array, uint8_t * data, size_t len )
{
DynamicArray tmp;
tmp.size = array.size + len;
tmp.data = new (nothrow) uint8_t[ tmp.size ];
if ( tmp.data != nullptr )
{
if ( array.data != nullptr )
{
memcpy( tmp.data, array.data, array.size );
delete[] array.data;
}
memcpy( tmp.data + array.size, data, len );
array.data = tmp.data;
array.size = tmp.size;
}
else
{
printf("sorry, couldn't add to array, memory allocation failed!\n");
}
}
myClass test;
int main()
{
uint8_t a[] = { 10, 20, 30, 40, 50, 60, 70 };
uint8_t b[] = { 80, 90, 100 };
test.addToArray( test.myDynamicArray1, a, 7 );
test.addToArray( test.myDynamicArray2, b, 2 );
test.addToArray( test.myDynamicArray1, b, 3 );
test.addToArray( test.myDynamicArray2, a, 5 );
for ( size_t i = 0; i < test.myDynamicArray1.size; i++ )
{
printf( "test.myDynamicArray1.data[%d] = %d\n", i, test.myDynamicArray1.data[i] );
}
printf( "\n" );
for ( size_t i = 0; i < test.myDynamicArray2.size; i++ )
{
printf( "test.myDynamicArray2.data[%d] = %d\n", i, test.myDynamicArray2.data[i] );
}
printf( "\n" );
size_t totalSize = test.myDynamicArray1.size + test.myDynamicArray2.size;
uint8_t * allData = new (nothrow) uint8_t[ totalSize ];
if ( allData != nullptr )
{
memcpy( allData, test.myDynamicArray1.data, test.myDynamicArray1.size );
memcpy( allData + test.myDynamicArray1.size, test.myDynamicArray2.data, test.myDynamicArray2.size );
for ( size_t i = 0; i < totalSize; i++ )
{
printf("allData[%d] = %d\n", i, allData[i] );
}
delete[] allData;
}
delete[] test.myDynamicArray1.data;
delete[] test.myDynamicArray2.data;
return 0;
}
|