I'm using focus callbacks to "Delete" the contents of a GtkEntry when someone clicks it (And puts it back if they leave it empty similar to the Title of questions on stack)
However, the variable is emptied when the function ends just like a local variable.
What am I doing wrong here?
// A place to store the character
char * store;
// When focussed, save the contents and empty the entry
void
use_key_entry_focus_in_event(GtkWidget *widget, GdkEvent *event, gpointer user_data){
if(strcmp(gtk_entry_get_text(G开发者_StackOverflow中文版TK_ENTRY(widget)), "")){
store = (char *) gtk_entry_get_text(GTK_ENTRY(widget));
}
gtk_entry_set_text(GTK_ENTRY(widget), "");
}
void
othercallback(){
printf("%s",store); // Returns nothing
}
Edit with help from answerers I wrote this (No malloc needed):
char store[2];
[...]
strcpy(store, (const char *) gtk_entry_get_text(GTK_ENTRY(widget)));
I don't know anything about the GTK library, but your problem is almost certainly that you're not taking a copy of the string, you're merely copying its address. You're then replacing the string with gtk_entry_set_text()
, so the original string disappears.
You will need to do something like:
const char *tmp = (char *) gtk_entry_get_text(GTK_ENTRY(widget));
store = malloc(strlen(tmp)+1);
strcpy(store, tmp);
And be careful to free(store)
at some point.
精彩评论