So, I have many entries in a 2D array in my GTK application, like this:
GtkWidget *entries[10][10];
for(int i = 0; i < 10; i++){
for(int j = 0; j < 10; j++){
entries[i][j] = gtk_entry_new();
}
}
And a button:
GtkWidget *btn;
btn = gtk_button_new_with_label("Calculate");
I want that, when the user clicks on the button, all the values in the entries be passed to the callback function in order to do some operations with the data.
I have:
g_signal_connect(btn, "clicked", G_CALLBACK(calculate), entries);
And a function called calculate():
void calculate(GtkWidget *btn, gpointer data){
double **values = (double **) data;
for(int i = 0; i < 10; i++){
for(int j = 0; j < 10; j++){
printf("%f ", gtk_entry_get_text(GTK_ENTRY(values[i][j])));
}
printf("\n");
}
}
Its name suggest that a calculation is going to be done. Indeed, I intend to develop the code to do so, but prior to it I need to get the data in the entries.
Why I am not successful in getting the data?
I changed g_signal_connect(btn, "clicked", G_CALLBACK(calculate), entries);
to g_signal_connect(btn, "clicked", G_CALLBACK(calculate), &entries[0][0]);
The function calculate now is:
void calculate(GtkWidget* btn, gpointer *data){
GtkWidget **values = (GtkWidget **) data;
for(int i = 0; i < 10; i++){
for(int j = 0; j < 10; j++){
printf("%s\n", gtk_entry_get_text(GTK_ENTRY(*(values+i) + j)));
}
}
}
I was successul in getting the text of the first entry, using gtk_entry_get_text(GTK_ENTRY(*values))
, but how can I get the texts of the other entries?
You are messing up the type of parameter you pass to your callback function:
GtkWidget *entries[10][10];
for(int i = 0; i < 10; i++){
for(int j = 0; j < 10; j++){
entries[i][j] = gtk_entry_new();
}
}
...
g_signal_connect(btn, "clicked", G_CALLBACK(calculate), entries);
This defines an array of 10*10 pointers.
But then you tell your compiler to treat it as a pointer to a pointer:
void calculate(GtkWidget *btn, gpointer data){
double **values = (double **) data;
This indicates a very different memory layout.
A 2D array is not the same as a pointer to pointer. Besides that your array contains pointers itself, not double
values.
What you need is this:
void calculate(GtkWidget *btn, gpointer data){
GtkWidget*(*values)[10] = (GtkWidget*(*)[10])data;
...
This should fix your issue with addressing your entries properly.
Besides that you may run into another problem.
If the array entries
is no longer valid at the time your callback function is called, you have an illegal memory access causing undefined behaviour.
You must make that array static or global. Or you must ensure that the function that did the initialization, never returns before the application is termianted.