big*_*man 1 c structure memcpy
如果我有一个定义如下的结构:
struct image{
unsigned int width, height;
unsigned char *data;
};
Run Code Online (Sandbox Code Playgroud)
这个类型的2个变量:
struct image image1;
struct image image2;
Run Code Online (Sandbox Code Playgroud)
我想将数据从image1传输到image2的数据(假设image1有一些数据写入,而image2有数据用malloc或calloc分配).怎么做到呢?非常感谢.
假设两个实例struct image指向相同的实例是不可取的,data则memcpy()不能用于复制structs.复印:
data根据源为目标缓冲区分配内存datawidth成员memcpy() data 成员.例如:
struct image* deep_copy_image(const struct image* img)
{
struct image* result = malloc(sizeof(*result));
if (result)
{
/* Assuming 'width' means "number of elements" in 'data'. */
result->width = img->width;
result->data = malloc(img->width);
if (result->data)
{
memcpy(result->data, img->data, result->width);
}
else
{
free(result);
result = NULL;
}
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
23156 次 |
| 最近记录: |