我需要在C中创建一系列按钮。我不确定我缺少什么,请帮助我。这是我的阵列:
GtkWidget *button[5];
int i;
for ( i =1; i<5; i++)
button[i] = gtk_button_new();
然后我创建剩下的按钮...我正在使用button [i]
然后在最后我这样做i++;
这可能不是最好的方式,但我不知道什么时候我创建数组,如何在其余的语句中传递按钮1,按钮2等?
请任何帮助表示赞赏。
附:我是C的新手,对我来说并不严厉,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++;
答案 0 :(得分:0)
你的for循环以索引变量(i)为1开始,但是在计算机的内存中,你用
声明的按钮数组的索引GtkWidget *按钮[5];
以索引0开始(i = 0) 例如,您的代码应该类似于:
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
然后使用按钮就像访问常规数组一样访问它们,例如:
button[0] = gtk_button_new_with_label("button 1");
你不需要for循环中的i ++,因为for循环在每个循环后自动递增迭代器(i变量)(这就是i ++结束时的那个(i = 0; i&lt; 5; i ++)确实)