在c中创建按钮gtk数组

标签 c arrays button widget gtk

我需要在 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++;

最佳答案

您的 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 变量)(这就是 for(i = 0; i < 5; i++ 末尾的 i++ 的内容) )确实)

关于在c中创建按钮gtk数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36783214/

相关文章:

c - 使用 Xcode 选项 Generate Output>Assembly 查看 C 文件的汇编代码

c - 变量的定义与初始化

c - 任何程序员都必须知道 C 吗?是的,为什么?没有为什么?

Python - 对数组进行排序以在其中进行搜索的最有效方法

php - MySQL/PHP - 用于从数据库中删除多行的复选框数组

html - 将 CSS 应用于表单时遇到问题

android - 如何改变单选按钮的半径

javascript - 使用按钮在 iframe 中打开文件

c - 堆栈中的 fatal error

javascript - 比较两个数组的 Angular 并对其进行循环