【问题标题】:Select certain elements in array to create new array选择数组中的某些元素以创建新数组
【发布时间】:2020-07-09 12:30:04
【问题描述】:

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

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

谢谢。

【问题讨论】:

  • 在C语言中,你可以设置一个指针指向第一个元素,然后这个指针就像一个包含这些元素的数组一样。之后你想对数组做什么?您是否需要制作一个完全独立的新副本,以便一个可以更改或解除分配,而另一个保持不变(或单独更改)?您需要在您的问题中添加有关目标是什么的详细信息。
  • stackoverflow 不是免费的编码服务。请发布您尝试过的内容以及它与您想要的内容有何不同。

标签: c arrays memory-management declaration variable-length-array


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:
    #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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-12
      • 1970-01-01
      • 1970-01-01
      • 2019-03-20
      • 1970-01-01
      • 2021-10-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多