Select 数组中的某些元素创建新数组

Select certain elements in array to create new array

如何通过给出开始和结束索引号来 select 数组中一定数量的元素来创建新数组?

例如,如果我的原始数组是 {1,2,3,4,5,6},并且我将 x=0 和 y=2 作为它们的索引值,我将有一个新数组是{1,2,3}。

谢谢。

如果您的编译器支持可变长度数组,那么您可以按以下方式执行此操作

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

程序输出为

1 2 3

否则新数组应该动态分配,例如

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