C语言 从 C 中的数组创建子数组的最佳方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17763408/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Best method to create a sub array from an array in C
提问by poorvank
I have an array say a[3]={1,2,5}. I have to create another array a2[2]={2,5}.
我有一个数组说a[3]={1,2,5}。我必须创建另一个数组a2[2]={2,5}。
What I have tried is to just create a new array a2[]and just copy all the elements from the required position range.
我尝试过的只是创建一个新数组,a2[]然后复制所需位置范围内的所有元素。
Is there any other method to accomplish this in C?.
有没有其他方法可以在 C 中完成此操作?
回答by BLUEPIXY
memcpy(a2, &a[1], 2*sizeof(*a));
回答by ouah
Instead of having a second array, just use a pointer:
而不是有第二个数组,只需使用一个指针:
int a[3]={1,2,5};
int *p = &a[1];
If they have to be distinct, you have no choice other than to copy the array elements into a new array.
如果它们必须是不同的,除了将数组元素复制到新数组中之外,您别无选择。

