我正在尝试编写此 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 并且可能与您的架构高字节与 .c
对齐并将其也设置为 0。
因此 .c
变为 0,并且 .times
从未设置
关于c++ - 结构数组声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21126906/