复制数组的一个子集为用C另一个数组/数组切片 [英] Copying a subset of an array into another array / array slicing in C

查看:204
本文介绍了复制数组的一个子集为用C另一个数组/数组切片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C,有没有内置阵列切片机制?

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

像在Matlab例如
A(1:4)

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

将产生=

 1     1     1     1

我怎样才能在C ++中实现这一点?

How can I achieve this in C?

我试图寻找,但我能找到最接近的是这样的:<一href=\"http://cboard.cprogramming.com/c-programming/95772-how-do-array-subsets.html\">http://cboard.cprogramming.com/c-programming/95772-how-do-array-subsets.html

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]

subsetArray = &bigArray[someIndex]

但是,这并不完全返回切片阵列,而不是指针到切片阵列的第一个元素...

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

非常感谢

推荐答案

感谢大家指出有在C没有这样的内置机制。

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

我试着用什么@Afonso冢本建议,但我意识到我需要多维数组的解决方案。所以,我结束了写我自己的函数。我把它放在这里,以防其他​​人正在寻找类似的答案:

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];
        }
    }
}

所以我输入(原始数组)和B是我的输出(切片数组)。
我调用该函数是这样的:

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

例如:

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

这将产生一个结果(多维排列B [1] [4]),在Matlab是等于A的结果(target_row,1:4)。

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

我是新的C所以请再纠正我,如果我错了,或者这个code可以变得更好...谢谢:)

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

这篇关于复制数组的一个子集为用C另一个数组/数组切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆