Re: GTK Casting Problem
- From: Mariano Suárez-Alvarez <msuarezalvarez arnet com ar>
- To: Chris <chrishax comcast net>
- Cc: gtklist <gtk-list gnome org>
- Subject: Re: GTK Casting Problem
- Date: Tue, 28 Nov 2006 22:22:20 -0300
On Tue, 2006-11-28 at 17:27 -0700, Chris wrote:
> Hello,
>
> I am new to gtk.
> To learn the language I am writing simple
> programs.
> I want to be able to create 3 buttons, named
> Button 1, Button 2 & Button 3.
> If I explicitly initialize them it works.
> When I pull the Initilize into a for loop
> things start to go wrong.
> I think that I am either not using the proper type
> or not properly casting them.
> The result is a segmentation error when I compile
> which I think means a pointer is not correct.
> If anyone knows how to fix this issue, it would be
> greatly appreciated.
> I have placed in bold the two sections
> that I think apply to the problem.
>
> My code is as follows:
>
> #include <stdlib.h>
> #include <stdio.h>
> #include <string.h>
> #include <gtk/gtk.h>
>
> [... snip ...]
>
> for (i=1; i<=3; i=i+1)
> {
>
> *label = (gpointer)"Button ";
Here you are assigning to '*label', yet you have not yet initialized
'label'. Hence the crash. (Indeed, gcc does not even compile this code)
> strcat (label, (gpointer) i);
This does not make much sense.
> button = gtk_button_new_with_label ((gchar *)label);
> [... snip ...]
> }
Here comes code that does a bit better:
/************************** begin example **************************/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <gtk/gtk.h>
static void
button_cb (GtkWidget *widget, gpointer data)
{
g_print ("Hello - %s was pressed\n", (gchar *) data);
}
static void
delete_event_cb (GtkWidget *widget, GdkEvent *event, gpointer data)
{
g_print ("A delete event has occurred\n");
gtk_main_quit();
}
int
main (int argc, char *argv[])
{
GtkWidget *window;
GtkWidget *button;
GtkWidget *box1;
gint i;
gtk_init (&argc, &argv);
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_window_set_title (GTK_WINDOW (window), "Test Program");
gtk_container_set_border_width (GTK_CONTAINER (window), 50);
g_signal_connect (G_OBJECT (window), "delete_event",
G_CALLBACK (delete_event_cb), NULL);
box1 = gtk_hbox_new (FALSE, 0);
gtk_container_add (GTK_CONTAINER (window), box1);
for (i=1; i<=3; i=i+1)
{
char *label;
label = g_strdup_printf ("Button %d", i);
button = gtk_button_new_with_label (label);
g_free (label);
g_signal_connect (G_OBJECT (button), "clicked",
G_CALLBACK (button_cb), label);
gtk_box_pack_start (GTK_BOX(box1), button, TRUE, TRUE, 0);
}
gtk_widget_show_all (window);
gtk_main ();
return 0;
}
/************************** end example **************************/
Hope this helps a bit.
You should probably consult a C book, by the way.
-- m
--
Mariano Su�z-Alvarez
http://www.gnome.org/~mariano
[
Date Prev][
Date Next] [
Thread Prev][
Thread Next]
[
Thread Index]
[
Date Index]
[
Author Index]