我怎么可以连接在C中的两个阵列? [英] How can I concatenate two arrays in C?

查看:191
本文介绍了我怎么可以连接在C中的两个阵列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何连接两个阵列以获得含有原数组的元素单一阵列?

How do I concatenate two arrays to get a single array containing the elements of both original arrays?

推荐答案

在C数组简单地是一个连续的内存区,一个指向其开始*。因此,合并它们包括:

Arrays in C simply are a contiguous area of memory, with a pointer to their start*. So merging them involves:

  1. 找到了数组a和b的长度,(你可能需要知道的元素数和的sizeof 每个元素)
  2. 分配(的malloc )的新数组C,它是A + B的大小。
  3. 复制(的memcpy )从A内存为C,
  4. 从b将存储到C + A(参见图1)的长度。
  5. 您可能还需要取消分配(免费)A和B的记忆。
  1. Find the length of the arrays A and B, (you will probably need to know the number of elements and the sizeof each element)
  2. Allocating (malloc) a new array C that is the size of A + B.
  3. Copy (memcpy) the memory from A to C,
  4. Copy the memory from B to C + the length of A (see 1).
  5. You might want also to de-allocate (free) the memory of A and B.

请注意,这是一个昂贵的操作,但是这是基本理论。如果您正在使用一个库,它提供了一些抽象,你可能会更好。如果A和B是比较复杂的,然后一个简单的数组(比如排序数组),您需要做聪明的复制,然后步骤3和4(参见:<一href="http://stackoverflow.com/questions/1700182/how-do-i-merge-two-arrays-having-different-values-into-one-array">how我该合并具有不同的值到一个数组)两个数组。

Note that this is an expensive operation, but this is the basic theory. If you are using a library that provides some abstraction, you might be better off. If A and B are more complicated then a simple array (e.g. sorted arrays), you will need to do smarter copying then steps 3 and 4 (see: how do i merge two arrays having different values into one array).


  • 虽然这个问题的目的,指针的解释就足够了,严格来说(和平息下面的评论者):C的的数组的概念,即可以在没有语法使用的指针。实现明智的,但是,一个C阵列和一个连续的内存区,指针都足够接近,他们可以,而且经常是,交替使用。
  • Although for the purpose of this question, the pointer explanation will suffice, strictly speaking (and for pacifying the commenter below): C has the concept of an array, that can be used without the syntax of pointers. Implementation wise, however, a C array and a contiguous area of memory, with a pointer are close enough they can be, and often are, used interchangeably.

这篇关于我怎么可以连接在C中的两个阵列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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