Copying a subset of an array into another array / array slicing in C

前端 未结 3 728
面向向阳花
面向向阳花 2020-12-16 16:58

In C, is there any built-in array slicing mechanism?

Like in Matlab for example, A(1:4)

would produce =

 1     1     1     1
<
3条回答
  •  爱一瞬间的悲伤
    2020-12-16 17:50

    Thanks everyone for pointing out that there is no such built-in mechanism in C.

    I tried using what @Afonso Tsukamoto suggested but I realized I needed a solution for multi-dimensional array. So I ended up writing my own function. I will put it in here in case anyone else is looking for similar answer:

    void GetSlicedMultiArray4Col(int A[][4], int mrow, int mcol, int B[1][4], int sliced_mrow)
    {
        int row, col;
        sliced_mrow = sliced_mrow - 1; //cause in C, index starts from 0
        for(row=0; row < mrow; row++)
        {
            for (col=0; col < mcol; col++)
            {
                if (row==sliced_mrow) B[0][col]=A[row][col];
            }
        }
    }
    

    So A is my input (original array) and B is my output (the sliced array). I call the function like this:

    GetSlicedMultiArray4Col(A, A_rows, A_cols, B, target_row);
    

    For example:

    int A[][4] = {{1,2,3,4},{1,1,1,1},{3,3,3,3}};
    int A_rows = 3; 
    int A_cols = 4; 
    int B[1][4]; //my subset
    int target_row = 1;
    
    GetSlicedMultiArray4Col(A, A_rows, A_cols, B, target_row);
    

    This will produce a result (multidimensional array B[1][4]) that in Matlab is equal to the result of A(target_row,1:4).

    I am new to C so please correct me if I'm wrong or if this code can be made better... thanks again :)

提交回复
热议问题