不知道如何访问这些元素

cant figure out how to acces these elements

本文关键字:元素 访问 何访问 不知道      更新时间:2023-10-16

这是我的标题

#include <SDL.h>
class Grid
{
public:
int** Cells;
int x;
int y;
SDL_Color* palette[255];
Grid(int,int,int);
~Grid();
void DrawGrid(SDL_Renderer*);
void SetPalette(int c, int r, int g, int b, int a);
};

这是我的来源:

Grid::Grid(int a,int b,int s)
{
std::cout << "grid constructed";
x = a;
y = b;
Grid::Cells = (int**) malloc(x*s);
for (int i = 0;i < x;i++)
{
    Grid::Cells[i] = (int*)malloc(y*s);
}
    SetPalette(1, 255, 255, 255, 0);
}
void Grid::DrawGrid(SDL_Renderer* renderer)
{
        std::cout << Grid::palette[Cells[i][o]].r << " : " << Cells[i][o];
        SDL_SetRenderDrawColor(renderer, palette[Cells[i][o]].r, palette[Cells[i][o]].g, palette[Cells[i][o]].b, palette[Cells[i][o]].a);
        SDL_RenderDrawPoint(renderer, i, o);
}
void Grid::SetPalette(int c, int r, int g, int b, int a)
{
palette[c].r = r;

我也有绿色,蓝色和alpha}

表示表达式必须具有类类型。我该如何修复我已经努力想弄明白了。所以我希望我至少能得到一个答案

我删除了一些不相关的代码,这样就不会占用太多的空间

您没有为调色板元素分配内存。如果不修改数据布局(这很糟糕,见下文),您至少需要在构造函数中分配元素(在SetPalette之前):

for(int i = 0; i != 255; i++) {
    palette[i] = new SDL_Color;
}

(你还需要释放这些内存,例如在destructor中)。

当调色板声明为SDL_Color* palette[255];时,表达式palette[c]具有SDL_Color*类型。使用.操作符访问结构字段需要结构,而不是指针-因此直接解决方案是palette[c]->r(或手动解引用并使用.,但这正是->所做的)。

然而,分配这么多这么小的对象的成本相对较高,在给定的示例中没有必要这样做。如果您的调色板大小是恒定的(因为它是),您可以使用SDL_Color palette[255]并删除所有分配/释放代码(并且不需要->,因为palette[c]的类型现在是SDL_Color)。如果大小在编译时不知道-你可以用单个分配(mallocnew[])来分配颜色数组。如果大小在运行时发生变化,使用vector可能更容易。