I want to create a 10x20 array of type GtkWidget. I want to make each of them a GtkEventBox in which I will attach a label.
How am I supposed to create and use a 2D GtkWidget* array?
This is what I've tried so far:
//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);
I would like to point out that I am fairly new to C and I don't know how to use malloc
(but I suspect that I should make use of it, now).
I found a solution:
Initialize array as:
GtkWidget **myarray;
myarray = g_new(GtkWidget *, ROWS*COLUMNS);
then access specific row and column using the function:
int returnPosAt(int row, int column){
return row*COLUMNS+column;
}
so, then, you can call
myarray[returnPosAt(i, j)]=gtk_event_box_new();
So, actually you have an 1D array and by calling the function you get the corresponding 1D pos of your 2D position (i, j).