结构声明数组

时间:2014-01-15 00:28:11

标签: c++ struct

我正在尝试编写这个C ++函数,我试图在Sequences数组中设置每个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;
}

如果有人能弄明白为什么会这样,那就太好了。

1 个答案:

答案 0 :(得分:1)

您可能想要更改:

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

为:

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

因此,您可以更改.times成员,否则您将覆盖.c成员。现在你将.c设置为'a'。然后将.c设置为103(counter+1)。哪个是int,并且可能与您的archetecture高字节正在与.c对齐并将其设置为0.

所以.c获得0,.times永远不会设置