gpt4 book ai didi

c - 范围问题 : External variable not stored

转载 作者:行者123 更新时间:2023-11-30 16:01:54 25 4
gpt4 key购买 nike

当有人点击 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)));

最佳答案

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

您需要执行以下操作:

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

并且要小心在某些时候释放(存储)

关于c - 范围问题 : External variable not stored,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5859860/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com