Search code examples
carraysmemory-managementdeclarationvariable-length-array

Select certain elements in array to create new array


How could I select a certain number of elements from an array by giving a start and ending index number to create a new array?

For example, if my original array was {1,2,3,4,5,6}, and I say x=0 and y=2 for their index values, I would have a new array that is {1,2,3}.

Thank you.


Solution

  • If your compiler supports variable length arrays then you can do this the following way

    #include <stdio.h>
    #include <string.h>
    
    int main(void) 
    {
        int a[] = { 1, 2, 3, 4, 5, 6 };
        size_t n1 = 0, n2 = 2;
        int b[n2 - n1 + 1];
    
        memcpy( b, a + n1, ( n2 - n1 + 1 ) * sizeof( int ) );
    
        size_t n = sizeof( b ) / sizeof( *b );
    
        for ( size_t i = 0; i < n; i++ )
        {
            printf( "%d ", b[i] );
        }
    
        putchar( '\n' );
    
        return 0;
    }
    

    The program output is

    1 2 3
    

    Otherwise the new array should be allocated dynamically as for example

    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    int main(void) 
    {
        int a[] = { 1, 2, 3, 4, 5, 6 };
        size_t n1 = 0, n2 = 2;
    
        size_t n = n2 - n1 + 1;
        int *b = malloc( n * sizeof( *b ) );
    
        memcpy( b, a + n1, n * sizeof( int ) );
    
        for ( size_t i = 0; i < n; i++ )
        {
            printf( "%d ", b[i] );
        }
    
        putchar( '\n' );
    
        free( b );
    
        return 0;
    }