创建 2D GtkWidget 数组

标签 c multidimensional-array segmentation-fault gtk background-color

我想创建一个 GtkWidget 类型的 10x20 数组。我想让它们每个都成为一个 GtkEventBox,我将在其中附加一个标签。

我应该如何创建和使用 2D GtkWidget* 数组?

这是我迄今为止尝试过的:

//global variable:
GtkWidget *labelPlate[ROWS][COLUMNS];
...
...
inside the function that creates the table and attaches the event boxes to it
//my table, where the EventBoxes will be attached to
GtkWidget *finalPlateTable = gtk_table_new (10, 20, TRUE);

int i, j;
for(i = 0; i<ROWS; i++){
    for(j=0 ; j<COLUMNS; j++){
        //Make a char with the current float and create a label with it.

        char finalString[14];
        sprintf(finalString, "%.2f", plate[i][j]);

        GtkWidget *label = gtk_label_new(finalString);;

        //Labels cannot have bg color, so attach each label to an event box
        /*HERE I GET SEG FAULT*/
        labelPlate[i][j]=gtk_event_box_new();

                    //adding the label to my eventbox
        gtk_container_add(GTK_CONTAINER(labelPlate[i][j]), label);

        //Add the corresponding bg color to each event box
        GdkColor color;
        switch(scalePlate[i][j]){
                            ...
                            ...
            break;
        }
                    //coloring the event box with the corresponding background
        gtk_widget_modify_bg ( GTK_WIDGET(labelPlate[i][j]), GTK_STATE_NORMAL, &color);
                    //attach the event box to the appropriate location of my table
        gtk_table_attach_defaults (GTK_TABLE (finalPlateTable), labelPlate[i][j], j, j+1, i, i+1);
        //show them!
        gtk_widget_show(label);
        gtk_widget_realize(labelPlate[i][j]);
    }
}
//adding the table to my vertical box, and show both of them
gtk_box_pack_start(GTK_BOX (verticalBox), finalPlateTable, TRUE, TRUE, 10);

gtk_widget_show (finalPlateTable);
gtk_widget_show (verticalBox);

我想指出,我对C相当陌生,而且我不知道如何使用malloc(但我怀疑我应该利用它,现在)。

最佳答案

我找到了解决方案:

将数组初始化为:

GtkWidget **myarray;
myarray = g_new(GtkWidget *, ROWS*COLUMNS);

然后使用以下函数访问特定的行和列:

int returnPosAt(int row, int column){
    return row*COLUMNS+column;
}

那么,你可以打电话

myarray[returnPosAt(i, j)]=gtk_event_box_new();

所以,实际上你有一个 1D 数组,通过调用该函数,你可以获得 2D 位置 (i, j) 的相应 1D pos。

关于创建 2D GtkWidget 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15728096/

相关文章:

c - 为什么 C 中二维数组的内容通过函数调用持久存在?

c++ - 为什么这个结构的大小是 3 而不是 2?

python - 在python中将整数转换为大端二进制文件

Java:对数组列表进行排序并以二维数组形式返回

c - 减少 ATmega8 的 C 代码大小

c - 我的终端仅打印 main 的第一个输出

C# - 多维 int 数组

opencv - 段错误 OpenCV/Facedetect.c/CentOS 6 64Bit

c - 将指针改组为指向结构的指针

c - 仅在不使用调试器时出现段错误