首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在C中使用memcpy()将数组复制到数组中

如何在C中使用memcpy()将数组复制到数组中
EN

Stack Overflow用户
提问于 2013-03-28 23:04:01
回答 4查看 26.6K关注 0票数 6

我正在尝试从另一个数组a复制数组(temp)。但我认为这是不可能发生的。

Fig-1

代码语言:javascript
复制
int main()
{
    typedef int arr_1[3];
    arr_1 arr[4];
    arr_1 *temp;
    arr_1 a[3] = {1, 2, 3};
    memset(&temp, 0, sizeof(temp));
    memcpy(temp, a, sizeof(temp));
}

但当我尝试下面这样的简单程序时,

Fig-2

代码语言:javascript
复制
 main()
    {
    int abc[3], def[3];
    def[3] = {1, 2, 3};
    memcpy(abc, def, sizeof(abc));
    }

上面的代码(fig-2)对我来说工作得很好。但是fig-1不为我工作。两者几乎是一样的。但是为什么fig-1不工作呢?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2013-03-28 23:08:04

例如,您必须使用malloc()temp分配内存。现在它只是一个未初始化的指针。

票数 5
EN

Stack Overflow用户

发布于 2013-03-28 23:05:35

因为temp不是数组,所以它是一个指针,因此sizeof(temp)与数组完全没有关系。

您希望将memcpy更改为使用sizeof(a)。在复制到temp之前,您还需要给它一个合理的值,否则程序会有未定义的行为。

票数 9
EN

Stack Overflow用户

发布于 2018-08-02 23:12:42

我知道,我迟到了。但当我读到前面的答案时,我想“你不需要所有这些变量”

使用您的简单示例:

代码语言:javascript
复制
int abc[3], def[3]; //abs is destination and def is source
def[3] = {1, 2, 3};
memcpy(abc, def, 3*sizeof(int)); //you can do sizeof(int) as you have here an array of int.

但最好使用变量"const int array_size = 3“或"#define ARRAY_SIZE 3”来定义数组大小。然后你只需要将"3“替换为"ARRAY_SIZE”,它就可以做同样的工作,并避免大小错误。

对于你真正的问题,你可以这样做:

代码语言:javascript
复制
#define ARRAY_SIZE 3

typedef int arr_1[ARRAY_SIZE];
arr_1 arr[ARRAY_SIZE+1];//it is useless here
arr_1 *temp = (arr_1 *) malloc(sizeof(arr_1)); //it is your destination, but you have a pointer of array
arr_1 a[ARRAY_SIZE] = {1, 2, 3};//it is your source

//by doing sizeof((*temp)[0])
//you do not care about the type of you array pointer
//you are sure to take the good size --> it fills your array with 0
memset((*temp), 0, (ARRAY_SIZE+1)*sizeof((*temp)[0])); 

//same logic
//but you destination is (*temp) because you have a pointer of array
//it means that your array arr and a have the same type
memcpy((*temp), a, ARRAY_SIZE * sizeof(a[0]));  

//by the way, the las cell of arr is still 0
//and a pointer is close to an array. If you do "tmp = a;" it works.
//but it is not a copy, you just give the a's reference to tmp
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15685240

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档