结构声明的数组
Array of structs declaration
我正试图编写这个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
从未设置
相关文章:
- 无法将字符串数组声明为类成员而不是字符 (C++)
- 为什么从函数返回数组时需要将数组声明为静态数组.(C++)
- 在 c++ 中直接访问的内联数组声明
- 由于 2D 数组声明,C++ 14 中的运行时错误
- 如何将char数组声明为函数参数?或告诉我此代码中还有其他问题?
- 来自函数参数的 C++ 静态数组声明
- C++ 中的动态数组声明
- C++数组声明
- 数组声明中的错误:表达式必须具有常量值
- 程序随数组声明崩溃
- 运行时和编译时的数组声明
- C++数组声明和初始化
- 带有常量表达式的数组声明
- C ,数组声明,模板,链接器错误
- 如何用'n'维数组声明 std::vector?
- 数组声明上的编译器错误
- 这是什么数组声明
- 头文件类中的数组声明
- 节点数组声明
- 在静态数组声明中使用了两次C++常量