OneBite.Dev - Coding blog in a bite size

extract a sub-array from an array in C

Code snippet on how to extract a sub-array from an array in C

  int* extractSubarray(int* array, int start, int end) 
{ 
    int size = end - start + 1; 
    int* subarray = (int*)malloc(sizeof(int) * size); 

    for (int i = 0; i < size; i++) 
        subarray[i] = array[start + i]; 

    return subarray; 
} 

This code extracts a sub-array from an array in C. First, we create a function called extractSubarray() which takes three arguments: an array, a start index and an end index. Next, we define a size variable which is set to the difference between the end and start index, plus one. We then allocate memory for a new sub-array with the same size as our initial size variable. Finally, we use a for loop to assign the values of our initial array to the sub-array. Once the array is populated, we return it.

c