如何阵列分成用C两个数组 [英] How to split array into two arrays in C

查看:160
本文介绍了如何阵列分成用C两个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有C中的数组

int array[6] = {1,2,3,4,5,6}

我怎么能分裂成

{1,2,3}

{4,5,6}

请问使用的memcpy这是可能的?

Would this be possible using memcpy?

感谢你,

NONONO

推荐答案

当然。这种简单的解决方法是使用的malloc ,然后用的memcpy 来将数据复制到两个数组分配两个新的阵列。

Sure. The straightforward solution is to allocate two new arrays using malloc and then using memcpy to copy the data into the two arrays.

int array[6] = {1,2,3,4,5,6}
int *firstHalf = malloc(3 * sizeof(int));
if (!firstHalf) {
  /* handle error */
}

int *secondHalf = malloc(3 * sizeof(int));
if (!secondHalf) {
  /* handle error */
}

memcpy(firstHalf, array, 3 * sizeof(int));
memcpy(secondHalf, array + 3, 3 * sizeof(int));

然而,如果原来的数组存在足够长的时间,你甚至不需要这么做。通过使用指针到原来的数组,你可以只'分裂'的阵列分为两个新的数组:

However, in case the original array exists long enough, you might not even need to do that. You could just 'split' the array into two new arrays by using pointers into the original array:

int array[6] = {1,2,3,4,5,6}
int *firstHalf = array;
int *secondHalf = array + 3;

这篇关于如何阵列分成用C两个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆