范围问题:未存储外部变量
当有人单击 GtkEntry 时,我使用焦点回调来“删除”它的内容(如果他们将其保留为空,类似于堆栈上的问题标题,则将其放回原处)
但是,当函数结束时,变量将被清空,就像局部变量。
我在这里做错了什么?
// 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(GTK_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
}
在回答者的帮助下编辑我写的(不需要 malloc):
char store[2];
[...]
strcpy(store, (const char *) gtk_entry_get_text(GTK_ENTRY(widget)));
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(GTK_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)));
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我对 GTK 库一无所知,但您的问题几乎可以肯定是您没有获取字符串的副本,而只是复制其地址。然后,您将该字符串替换为
gtk_entry_set_text()
,这样原始字符串就会消失。您需要执行以下操作:
并在某些时候小心
free(store)
。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:
And be careful to
free(store)
at some point.