Creating array of buttons gtk in c

2020-05-09 09:24发布

问题:

I need to create array of buttons in C. I am not sure what am I missing, please help me. Here is my array:

GtkWidget *button[5];
int i;
for ( i =1; i<5; i++)
        button[i] = gtk_button_new();

Then I creating the rest of the buttons... I am using button [i] and then at the end i do this i++; This probably not the best way, but i am just not sure when I create the array, how do I pass button 1, button 2 and etc in the rest of my statements? Please any help appreciated. p.s. I am new in C, dont be harsh on me, ty:)

 /* Creates a new button with the label "Button 1". */
button[i] = gtk_button_new_with_label ("Button 1");

/* Now when the button is clicked, we call the "callback" function
 * with a pointer to "button 1" as its argiument */
g_signal_connect (button[i], "clicked",
                  G_CALLBACK (callback), "Run button 1");

/* Instead of gtk_container_add, we pack this button into the invisible
 * box, which has been packed into the window. */
gtk_box_pack_start (GTK_BOX (box1), button[i], TRUE, TRUE, 0);

/* Always remember this step, this tells GTK that our preparation for
 * this button is complete, and it can now be displayed. */
gtk_widget_show (button[i]);
i++;

回答1:

your for loop starts with an index variable (i) of 1 however in the computer's memory the index to the array of buttons that you declared with

GtkWidget *button[5];

starts with an index of 0 (i = 0) so for example your code should look something like:

GtkWidget *button[5];
//not necessary since c99 can declare inside for() e.g for(int i = 0; i < 5; i++)
int i;
for(i = 0; i < 5; i++)
{
    button[i] = gtk_button_new();
}
//do other stuff

then to use the buttons just access them like you would a regular array eg:

 button[0] = gtk_button_new_with_label("button 1");

you do not need the i++ inside of the for loop because the for loop automatically increments the iterator (i variable) after every loop (this is what the i++ at the end of for(i = 0; i < 5; i++) does)