user6565727
user6565727

Reputation:

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]). 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?

Upvotes: 5

Views: 29474

Answers (4)

Alexander
Alexander

Reputation: 63227

You can manually increment the pointer by 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)

For a closer analogue to array slicing from other languages, try this function:

int *copy_array_slice(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!

Upvotes: 5

BobWanghz
BobWanghz

Reputation: 68

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.


int dst[4];
memcpy(dst,&arr[1],size(int) * 4);

Upvotes: 2

bluesawdust
bluesawdust

Reputation: 85

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

Upvotes: 2

Mr Pudin
Mr Pudin

Reputation: 70

Answer

Given you current code:

int arr[5] = {10, 2, 3, 5, 1};

You can duplicate the range 1..4 by:

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

Explanation

Arrays in c implemented as pointers (aka variables that hold memory addresses).

If you do arithmetic on the pointer, it will advance to the respective element. Example:

ptr + 1 //Next Element
ptr - 1 //Previous Element

Upvotes: 3

Related Questions