Re: Compile warning (newbie)

On Mon, 2007-04-16 at 23:09 -0700, William D. Tallman wrote:
> Then it should be like this?
> void edit_changed (GtkWidget *widget, gpointer *data)
> {
>     const gchar *str;
>     gchar *strcopy;
>     str = gtk_entry_get_text (GTK_ENTRY (widget));
>     strcopy = g_strdup(str);
>     g_print ("Entry changed to %s\n", strcopy);
>     free(strcopy);
> }

In your case, you don't need to strdup since you're not modifying the
string.  You only need to strdup if you need to manipulate a copy of the
string in some way.  For example,

strcopy=g_strdup(gtk_entry_get_text( GTK_ENTRY( widget )));
g_strcat(strcopy," random text added for my purposes");
//do something with strcopy

> I'm no whiz with C itself and have never used strdup.  IIUC, the
> template is as above, replacing the g_print with whatever is to be done
> with the copied string.  Is that correct?  If not, what don't I
> understand here?

I use strdup all the time, for the specific cases where I need to
manipulate a string that is being returned to me from a function.  See I
don't own the memory that I'm being given a pointer to.  Thus I can't
modify that memory directly (say to make it all lowercase or append text
to it).  I have to make my own copy.  

Note that many of the glib string utility functions already have a
built-in strdup.  For example, g_ascii_tolower() returns a duplicated
string that is all lowercase, which you will have to free later.

Generally speaking, if a function returns a const char * (or gchar),
that means you are getting a pointer to a string buffer that you should
not modify.  If you need to modify that string buffer, make a copy of it


> Thanks,
> Bill Tallman
> _______________________________________________
> gtk-list mailing list
> gtk-list gnome org

[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]