将结构的内容复制到另一个

标签 c struct copy ppm

我正在尝试将一个结构的内容复制到另一个相同类型的结构中。

不过,我希望能够更改一个结构的值而不影响另一个结构。

我正在处理阅读和编辑 PPM 文件。我有一个结构:

typedef struct {
    char format[4];
    char comments[MAX_COMMENT_LENGTH];
    int width, height, maxColourValue;
    PPMPixel **pixels;
} PPMImage;

然后我有一个复制函数来复制值,但是在分配不同的字段时出现错误。

我正在尝试将 newPPM 的字段复制到 messagePPM。

错误:

incompatible types when assigning to type 'char[4]' from type 'char *'
    messagePPM->format = newPPM->format;
incompatible types when assigning to type 'char[100]' from type 'char *'
    messagePPM->comments = newPPM->comments;

复制功能:

//A function to copy contents of one PPMImage to another
void copyPPM(PPMImage *newPPM, PPMImage *messagePPM) {

    messagePPM->format = newPPM->format;
    messagePPM->comments = newPPM->comments;
    messagePPM->width = newPPM->width;
    messagePPM->height = newPPM->height;
    messagePPM->maxColourValue = newPPM->maxColourValue;
    messagePPM->pixels = newPPM->pixels;

如何解决我的错误? 以这种方式复制字段是否会实现我的目标?

最佳答案

您可以通过简单的赋值将一个结构的内容复制到另一个:

void copyPPM(PPMImage *newPPM, PPMImage *messagePPM)  {
    *newPPM = *messagePPM;
}

这意味着您甚至不需要函数。

然而,这些结构将共享像素 数组。如果你想复制它,你将需要分配一个副本并复制内容。

将一个结构复制到另一个结构上也可能导致目标的像素数组丢失。

如果要对结构进行深拷贝,需要这样为像素分配新的数组:

void copyPPM(PPMImage *newPPM, PPMImage *messagePPM)  {
    *newPPM = *messagePPM;
    if (newPPM->pixels) {
        newPPM->pixels = malloc(newPPM->height * sizeof(*newPPM->pixels));
        for (int i = 0; i < newPPM->height; i++) {
            newPPM->pixels[i] = malloc(newPPM->width * sizeof(*newPPM->pixels[i]);
            memcpy(newPPM->pixels[i], messagePPM->pixels[i],
                   newPPM->width * sizeof(*newPPM->pixels[i]));
        }
    }
}

关于将结构的内容复制到另一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35327794/

相关文章:

c - 为什么不只在 header 中声明结构?这不会使 include-guards 变得不必要吗?

c - 在c中打开/读取文本文件

c - memcpy 的内部实现是如何工作的?

python - Errno 22 无效 (wb) 或文件名。 Python Shutil.copy

c - 在c中为OpenGL读取jpg纹理

python - 使用 Winsock 获取套接字列表

c - 如何在c中声明一个结构?

C# 使用其他域/用户名/密码将文件复制到另一个目录

c - 为什么我在终端中没有 getch() 就看不到 hello world 的输出;虽然我可以使用 memcpy() 函数查看多个 printf 吗?

c - C中的break语句