如何在C中将数组拆分为两个数组
假设我在 C 中有一个数组,
int array[6] = {1,2,3,4,5,6}
我如何将其拆分为
{1,2,3}
和
{4,5,6}
这可以使用 memcpy 吗?
谢谢你,
诺诺诺
Say i have an array in C
int array[6] = {1,2,3,4,5,6}
how could I split this into
{1,2,3}
and
{4,5,6}
Would this be possible using memcpy?
Thank You,
nonono
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当然。最简单的解决方案是使用 malloc 分配两个新数组,然后使用 memcpy 将数据复制到这两个数组中。
但是,如果原始数组存在足够长的时间,您可能甚至不需要这样做。您可以通过使用指向原始数组的指针将数组“拆分”为两个新数组:
Sure. The straightforward solution is to allocate two new arrays using
malloc
and then usingmemcpy
to copy the data into the two arrays.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:
你不必把它们分开。如果有,
则有第二个数组。当您将数组传递给函数时,它无论如何都会变成指针。
You don't have to split them. If you have
you have the second array. When you pass an array to a function, it's turned into a pointer anyway.
了解 memcpy 工作原理的神奇之处,无需专门拆分数组。目标数组中所做的更改将自动转到源数组,反之亦然。
See the magic how memcpy works, no need to exclusively split the arrays. The changes made in destination array are automatically go to source array and vise versa.