gpt4 book ai didi

c - 在内存中分配的修改后的结构在函数结束后不保留值

转载 作者:太空宇宙 更新时间:2023-11-04 08:23:51 25 4
gpt4 key购买 nike

我有几个结构:一个 HashTable,它包含一个指向 WordNode 的指针表,每个 WordNode 都包含一个指向 List 的指针,List 是由 ListNode 组成的链表。

我编写了一个函数来创建列表并将列表节点添加到 WordNode:

int addWord(char* word, HashTable* hash_table, int id)
{
WordNode* current = calloc(1, sizeof(WordNode));
current = hash_table->table[hash];

// ...

if(current->docs == NULL){
// Create a new list, and initialize it
List* list = calloc(1, sizeof(List));
list->head = NULL;
list->tail = NULL;

int occur = 1;
ListNode* list_node = AddNode(list); // Create the first node in the list

current->docs = list; // Link the WordNode to the list

// Fill in relevant details of ListNode
list_node->id= &id;
list_node->occurrences = &occur;
list_node->next = NULL;

这是我的功能,但由于它一直给我带来麻烦,我在其中添加了几行来测试它:

    printf("Testing:\n");
WordNode* wnode = calloc(1, sizeof(WordNode));
wnode = hash_table->table[hash];

List* my_list = calloc(1, sizeof(List));
my_list = wnode->docs;

ListNode* dnode = calloc(1, sizeof(ListNode));
dnode = my_list->head;

printf("Results: ocurrences: %d, id: %d\n",*((int*)dnode->occurrences),
*((int*)dnode->id));
printf("The dnode is %d\n", doc_node);

}

在 main 中调用时,函数内的测试代码会产生预期的输出:

Results: ocurrences: 1, id: 15
The dnode is 13867424

但是,紧跟在 main 函数调用之后的行中的相同测试会产生奇怪的输出,即使指针似乎指向相同的地址也是如此。

Results: ocurrences: 0, id: 54
The dnode is 13867424

可能与将新节点添加到列表的函数相关的代码:

ListNode* AddNode(List * list)
{

ListNode* node = calloc(1, sizeof(ListNode));
node->next = NULL;

if(list->tail == NULL){
list->head = node;
list->tail = node;
}
else{
list->tail->next = node;
list->tail = node;
}

return node;
}

我似乎无法弄清楚我做错了什么。在我看来,我以某种方式将结构作为局部变量处理,即使我正在为它们分配内存,这让我认为它们在函数完成后不应该改变。这可能是 C 程序员的初学者错误,但我似乎无法弄清楚我在哪里弄错了。任何帮助将不胜感激。

最佳答案

一组问题在代码中:

int addWord(char* word, HashTable* hash_table, int id)
{
…omitted…

int occur = 1;
ListNode* list_node = AddNode(list); // Create the first node in the list

current->docs = list; // Link the WordNode to the list

// Fill in relevant details of ListNode
list_node->id= &id;
list_node->occurrences = &occur;

您在结构中存储了一个指向参数的指针和一个指向局部变量的指针。在函数返回后取消引用其中任何一个是未定义的行为。那些占用的空间可以随时被编译器用于任何目的;它们可能会变得完全无效(但可能不会)。

为什么你的结构中有这两项的指针?当然,该结构应该只包含几个 int 成员,而不是 int * 成员!

如果您的代码在编译时出现警告,请不要将其提交给 SO;首先修复警告。或者寻求有关如何解决编译器警告的帮助。他们都很重要。在您职业生涯的这个阶段,请记住,编译器对 C 的了解比您多得多。如果它对您的代码中的某些内容发出警告,编译器的担心可能是正确的,并且代码可能在某些方面不正确。

您的代码没有显示 word 的使用位置 — 可能是您也没有复制该数据。

关于c - 在内存中分配的修改后的结构在函数结束后不保留值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31905417/

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