temo
temo

Reputation: 69

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.

Upvotes: 1

Views: 641

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 311048

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

Upvotes: 2

Aplet123
Aplet123

Reputation: 35522

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void print_arr(int* arr, int len) {
    for (int i = 0; i < len; i ++) {
        printf("%d", arr[i]);
        if (i != len - 1) {
            printf(" ");
        } else {
            printf("\n");
        }
    }
}

int main() {
    int arr1[] = {1, 2, 3, 4, 5, 6};
    int start, end;
    printf("input the beginning and the end: ");
    scanf("%d %d", &start, &end);
    int len = end - start + 1;
    // we use malloc to dynamically allocate an array of the correct size
    int* arr2 = (int*)malloc(len * sizeof(int));
    // we use memcpy to copy the values
    memcpy(arr2, arr1 + start, len * sizeof(int));
    print_arr(arr1, 6);
    print_arr(arr2, len);
    // we have to free the memory
    free(arr2);
    return 0;
}

Upvotes: 1

Related Questions