范围问题:未存储外部变量

发布于 2024-11-04 14:07:49 字数 738 浏览 0 评论 0原文

当有人单击 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

故事未完 2024-11-11 14:07:49

我对 GTK 库一无所知,但您的问题几乎可以肯定是您没有获取字符串的副本,而只是复制其地址。然后,您将该字符串替换为 gtk_entry_set_text(),这样原始字符串就会消失。

您需要执行以下操作:

const char *tmp = (char *) gtk_entry_get_text(GTK_ENTRY(widget));
store = malloc(strlen(tmp)+1);
strcpy(store, tmp);

并在某些时候小心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:

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文