Search code examples
carrayslist-manipulation

Reshaping an array from 1D to ND in C


I am having a lot of trouble trying to implement this on my own, so if anyone can point to, or describe an algorithm I'd be much obliged.

The problem statement

Given one dimensional flattened pointer int* i which would look something like this {1,2,3,4}, and given a list of dimensions in form of a list {2,2} reshape the 1D array to conform with specified dimensions. Overall after the procedure the array should look like {{1,2},{3,4}}.

I am basically asking if anyone knows the algorithm that is used in numpy.reshape.


Solution

  • A n-dimensional array in is nothing more than syntactic sugar for computing the offset inside a simple array, they look the same in memory (one contiguous block). Therefore, there's really no point in "reshaping" it, as this little sample demonstrates:

    #include <stdio.h>
    
    int data[] = {1,2,3,4};
    
    int main(void)
    {
        int *i = data;
    
        for (int n = 0; n < 4; ++n)
        {
            printf("i[%d] = %d\n", n, i[n]);
        }
    
        int (*j)[2] = (void *)i;
    
        for (int n1 = 0; n1 < 2; ++n1)
        {
            for (int n2 = 0; n2 < 2; ++n2)
            {
                printf("j[%d][%d] = %d\n", n1, n2, j[n1][n2]);
            }
        }
    
        return 0;
    }
    

    output:

    i[0] = 1
    i[1] = 2
    i[2] = 3
    i[3] = 4
    j[0][0] = 1
    j[0][1] = 2
    j[1][0] = 3
    j[1][1] = 4