为什么函数内部和函数外部的值不匹配?

Why is there a mismatch in the value inside the function and outside the function?

我正在尝试存储指向节点的指针数组。在 createlist() 函数中,我已经初始化了指针数组 linked_list_array[i] = createNode(-1); 数组中的每一项。

然后我用list->linkedLists = linked_list_array分配给了list->linkedLists
似乎一旦我 return list 回到主函数, list->linkedLists[0]->key 的值就改变了。
为什么值变了?

#include <stdio.h>
#include <stdlib.h>

#define NEG_INF (-32727)

struct leapList{
    
    int maxHeight;
    int curr_height;
    struct Node **linkedLists;
    double prob;
};

struct Node{
    struct Node* next;
    struct Node* below;
    int key;
};

struct Node* createNode(int key){
    struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
    new_node->next = NULL;
    new_node->below = NULL;
    new_node->key = key;
    return new_node;
}


struct leapList* createList(int maxheight, double p){
    struct leapList* list = (struct leapList*)malloc(sizeof(struct leapList));
    list->maxHeight = maxheight;
    list->prob = p;
    list->curr_height = 0;
    struct Node* linked_list_array[maxheight];
    for(int i=0;i<maxheight;i++){
        linked_list_array[i] = createNode(-1);
    }
    list->linkedLists = (linked_list_array);
    printf("key inside function: %d\n", list->linkedLists[0]->key);
    return list;
}
struct Node* insertNode(struct Node** headref, int key){
    struct Node* curr_node = NULL;
    struct Node* new_node = createNode(key);
    if(*headref == NULL || (*headref)->key >= key){
        new_node->next = *headref;
        *headref = new_node;
    }else{
        curr_node = *headref;
        while(curr_node->next!=NULL && curr_node->next->key < key){
            curr_node = curr_node->next;
        }
        new_node->next = curr_node->next;
        curr_node->next = new_node;
    }
    //printf("%d ", new_node->key);
    return new_node;
}


int main(int argc, const char * argv[]) {
    // insert code here...
    struct leapList* list = createList(5, 0.5);
    printf("key outside function: %d", list->linkedLists[0]->key);
    struct Node* head_node = createNode(-37273);

    
    insertNode(&head_node, 5);
    insertNode(&head_node, 3);
    insertNode(&head_node, 1);
    
    
    return 0;
}

这是我在 运行 程序后得到的

您将 list->linkedLists 设置为指向本地(“自动存储”)变量。

...
struct Node* linked_list_array[maxheight];
...
list->linkedLists = linked_list_array;
...

在函数 returns 之后访问 linked_list_array 不再合法,但这就是您最终要做的。这是未定义的行为。

您将需要 malloc 数组。