[英]Pass in part of an array as function argument
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]
). 我有一个数组
int arr[5] = {10, 2, 3, 5, 1}
10,2,3,5,1 int arr[5] = {10, 2, 3, 5, 1}
,我想将最后4个元素(基本上从索引1传递到index4)作为数组传递给参数(所以: [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? 有没有办法非常简单地做到这一点(比如在Ruby中你可以做arr [1..4]),还是我必须使用for循环?
You can manually increment the pointer by 1: 您可以手动将指针递增1:
your_function(arr + 1)
Pointer arithmetic in C implicitly accounts for the size of the elements, so adding 1 will actually add 1 * sizeof(int)
C中的指针算法隐含地考虑了元素的大小,因此添加1实际上会增加
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;
}
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! 一旦你完成它,请记得
free()
切片!
Given you current code: 鉴于您当前的代码:
int arr[5] = {10, 2, 3, 5, 1};
You can duplicate the range 1..4 by: 您可以通过以下方式复制范围1..4:
int arr_dup[4];
memcpy(arr_dup,arr+1,sizeof(int)*4);
Remember that your function definition should be a pointer, example: 请记住,您的函数定义应该是一个指针,例如:
void a_function(int *arr_arg); //Call via a_function(arr_dup);
Arrays in c implemented as pointers (aka variables that hold memory addresses). c中的数组实现为指针(也就是保存内存地址的变量)。
If you do arithmetic on the pointer, it will advance to the respective element. 如果对指针进行算术运算,它将前进到相应的元素。 Example:
例:
ptr + 1 //Next Element
ptr - 1 //Previous Element
#include <stdio.h>
#include <stdlib.h>
void my_function(int arr_size, int *arr)
{
int i;
for(i=0; i < arr_size; i++)
{
printf("[%d]:%d\n", i, arr[i]);
}
}
int main(int argc, char **argv)
{
int arr[] = { 10, 2, 3, 5, 1 };
(void)my_function(4, &arr[1]); /* TODO > use more flexible indexing */
return EXIT_SUCCESS;
}
I think you can use memcpy
, memcpy
can copy data byte to byte.In memmory,our data is binary,so even int
is 4 bytes,we can copy it byte to byte. 我认为你可以使用
memcpy
, memcpy
可以将数据字节复制到byte.In memmory,我们的数据是二进制的,所以即使int
是4个字节,我们也可以将它复制到字节。
int dst[4];
memcpy(dst,&arr[1],size(int) * 4);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.