c++ - 结构数组声明

标签 c++ struct

我正在尝试编写此 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/

相关文章:

c++ - 在哪里可以找到对 C++ 有状态虚拟基的很好的解释?

c - 删除列表时head如何连接到tail

C访问结构中的结构

C++ Map/Set 迭代器不可递增错误

c++ - MinGW 上的 localtime_r 支持

c++ - 如何识别类类型以将shared_ptr强制转换为该类型

c++ - 无法使用 boost 在 eclipse 中找到 libboost_system.so.1.43.0

c - 代码中制作 head 和 n 有什么区别

go - 从 SQL QueryRow 结果动态生成结构字段

c++ - 无递归初始化