将数组的一部分作为函数参数传递 [英] Pass in part of an array as function argument
问题描述
我有一个数组 int arr [5] = {10,2,3,5,1}
,我想传入最后4个元素(基本上从索引1到index4)作为数组的参数(因此: [2、3、5、1]
)。有没有一种方法可以非常简单地做到这一点(例如在Ruby中您将能够执行arr [1..4]),还是我必须使用for循环?
I have an array int arr[5] = {10, 2, 3, 5, 1}
, and I want to pass in the last 4 elements (basically from index 1 to index4) into an argument as an array (so: [2, 3, 5, 1]
). Is there a way to do this very simply (like how in Ruby you would be able to do arr[1..4]), or would I have to use a for loop?
推荐答案
您可以手动将指针增加1:
You can manually increment the pointer by 1:
your_function(arr + 1)
C语言中的指针算术隐式说明了元素的大小,因此加1将实际上添加 1 * sizeof(int)
Pointer arithmetic in C implicitly accounts for the size of the elements, so adding 1 will actually add 1 * sizeof(int)
要更类似于其他语言的数组切片,请尝试以下功能:
For a closer analogue to array slicing from other languages, try this function:
int *slice_array(int *array, int start, int end) {
int numElements = (end - start + 1)
int numBytes = sizeof(int) * numElements;
int *slice = malloc(numBytes);
memcpy(slice, array + start, numBytes)
return slice;
}
它在给定的开始索引和结束索引之间分割了一部分数组。完成切片后,请记住<< c $ c> free()!
It makes a slice of the array between the given start and end indices. Remember to free()
the slice once you're done with it!
这篇关于将数组的一部分作为函数参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!