我正在尝试将一个结构的内容复制到另一个相同类型的结构中。
不过,我希望能够更改一个结构的值而不影响另一个结构。
我正在处理阅读和编辑 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/