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
|
#include <cstdlib>
#include <iostream>
using namespace std;
#define SIZE 3
void* scramble (void* arr, int ElemSize, int n, int* indArr)
{
void* newArr = (void*) malloc(ElemSize * n);
char* new_ptr = reinterpret_cast<char *>(newArr);
char* orig_ptr = reinterpret_cast<char *>(arr);
char* orig_idx_ptr;
int* idx_ptr;
for ( int i=0 ; i < n ; i++ )
{
// newArr[i] = arr[indArr[i]];
idx_ptr = indArr + i; // Get next entry from indArr
orig_idx_ptr = orig_ptr +(*idx_ptr * ElemSize); // find element in arr to copy
memcpy(new_ptr, orig_idx_ptr, ElemSize); // copy it to the new array
new_ptr += ElemSize; // move newArr to next element ready for next copy
}
return newArr;
}
void main()
{
int arr[SIZE] = {100,200,300}; // main array
//char arr[SIZE] = {'a','b','c'};
//float arr[SIZE] = {1.5, 5.8, 9.24};
int n = SIZE; // array size
int indArr[SIZE] = {2,0,1}; // index array
int *p = NULL;
int *ptr;
p = (int *)scramble ( (void*)arr, sizeof(arr[0]), n, indArr );
ptr = p;
for (int i = 0; i < SIZE; i++)
{
cout << *ptr++ << endl;
}
}
|