Search code examples
cmemory-mapping

Can we map a array to another array in C, like mapping a file?


I have an array (1D), and other array of same size in different order (which will change according to the program situation) should also have the same value.

For example:

array1 = {1,2,3,4,5};

hence array2, should automatically have,

array2 = {4,2,3,1,5};

Some what you can say, i want to jumble up values according to my unique reference. But whenever parent array1 changes, array2 should also be updated at its respective indexes. Is it even possible? Array memory mapping? looping and saving to other array is taking time as this operation is iterated several times. I cannot do memcpy, because order can be different. Any pointers/helps/suggestions will be appreciated.


Solution

  • There's no magical way to do this. What you need to do is store the actual values somewhere, and then access them through a permutation stored separately. Here's some example code that uses strings so the permutation and the values are clearly distinct:

    char *strings[] = {"foo", "bar", "baz", "quux"};
    
    size_t memory_order[] = {0, 1, 2, 3};
    size_t sorted_order[] = {1, 2, 0, 3};
    
    // Get the k'th element in the memory order:
    strings[memory_order[k]];
    
    // Get the k'th element in the sorted order:
    strings[sorted_order[k]];