结构声明的数组

Array of structs declaration

本文关键字:数组 声明 结构      更新时间:2023-10-16

我正试图编写这个C++函数,在该函数中,我试图设置序列数组中的每个Sequence,但当我在调试时遵循代码时,我注意到数组没有改变。特别是:

compressed.data[compressedDataCounter].c = pic.data[i];
compressed.data[compressedDataCounter].times = counter+1;

似乎没有向数组添加任何新变量,只覆盖第一个变量我认为问题的根源在于声明:

CompressedPic compressed;
compressed.data = new Sequence[pic.height * pic.width];

这是代码的一部分:

struct  Sequence
{
char c;
int times;
};
struct  CompressedPic
{
int height;
int width;
Sequence* data;
};
struct  Picture
{
int height;
int width;
char* data;
};
CompressedPic  compressThePicture(Picture  pic) {
CompressedPic compressed;
compressed.data = new Sequence[pic.height * pic.width];
compressed.height = pic.height;
compressed.width = pic.width;
int compressedDataCounter=0;
for(int i=0; i<(pic.height * pic.width)-1; i++)
{
int counter = 0;
while(pic.data[i] == pic.data[i+1]) 
{
i++;
counter++;
}
compressed.data[compressedDataCounter].c = pic.data[i];
compressed.data[compressedDataCounter].times = counter+1;
compressedDataCounter++;
}
compressed.data[compressedDataCounter].times = -1;
return compressed;
}

如果有人能弄清楚为什么会发生这种事,那就太好了。

您可能需要更改:

compressed.data[compressedDataCounter].c = counter+1;

至:

compressed.data[compressedDataCounter].times = counter+1;

因此,您可以更改.times成员,否则您将覆盖您的.c成员。例如,现在您正在将.c设置为"a"。然后将.c设置为103(counter+1)。这是一个int,很可能与您的archtecture一样,高字节与.c对齐,并将其设置为0。

因此.c为0’d,而.times从未设置