Question

I've written the following generic function:

void* scramble(void* arr, int ElemSize, int n, int* indArr){
    void * res = malloc(n * ElemSize);
    int i;

    for (i = 0 ; i < n ; i++)
        memcpy((BYTE*)res+i*ElemSize, (BYTE*)arr+indArr[i]*ElemSize, ElemSize);

    return res;
}

The function gets an array, the size of each element, and number of elements in the array.
indArr is an array with indexes running from 0 to n-1 in any order.
The function returns a new array arranged according to indArr.

How can I use it to work with two dimensional arrays (or more)? I tried this, but it doesn't work:

int indArr[] = {2, 0, 1};
char names[][10] = {{"David"}, {"Daniel"}, {"Joni"}};
char **res;

res = (char**)scramble(names, sizeof(char*), 3, indArr);

for (i = 0 ; i < 3 ; i++)
    printf("%s ", res[i]);

Any thoughts? Thanks

Was it helpful?

Solution

names is an array of arrays.

The scrambler referrs to the outer array. The elements of the latter are the "strings". The size of each string is 10.

So call the scrambler like this:

res = (char**)scramble(names, 10, 3, indArr);

or

res = (char**)scramble(names, sizeof(*names), 3, indArr);

Update:

To be able to access the single elements of the inner array do as follows:

char (*res)[10] = (char (*)[10]) scramble(names, sizeof(*names), 3, indArr);

for (int i = 0; i < 3; ++i)
  printf("res[%d] = '%s'\n", i, res[i]);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top