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

▼魔方 西西 提交于 2019-11-29 18:13:59

问题


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

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

would produce =

 1     1     1     1

How can I achieve this in C?

I tried looking, but the closest I could find is this: http://cboard.cprogramming.com/c-programming/95772-how-do-array-subsets.html

subsetArray = &bigArray[someIndex]

But this does not exactly return the sliced array, instead pointer to the first element of the sliced array...

Many thanks


回答1:


Doing that in std C is not possible. You have to do it yourself. If you have a string, you can use string.h library who takes care of that, but for integers there's no library that I know. Besides that, after having what you have, the point from where you want to start your subset, is actually easy to implement.

Assuming you know the size of your 'main' array and that is an integer array, you can do this:

subset = malloc((arraySize-i)*sizeof(int)); //Where i is the place you want to start your subset. 

for(j=i;j<arraySize;j++)
   subset[j] = originalArray[j];

Hope this helps.




回答2:


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 :)




回答3:


In C,as far as I know, array name is just regarded as a const pointer. So you never know the size of the subset. And also you can assign a arrary to a new address. So you can simply use a pointer instead. But you should manage the size of the subset yourself.



来源:https://stackoverflow.com/questions/14618342/copying-a-subset-of-an-array-into-another-array-array-slicing-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!