You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

二叉搜索树插入时malloc空间分配及指针变量疑问解答

Hey Chris, let's work through your two BST questions step by step—they're great questions that get to the heart of how pointers work in C!

First, here's your code for reference (kept exactly as you shared):

struct node { int data; struct node* left; struct node* right; };
struct node* tree;
struct node* insert(struct node*, int);
void preorder(struct node*);
int main() {
    int option, val;
    struct node* ptr;
    tree = NULL;
    do {
        printf("\n ******MAIN MENU******* \n");
        printf("\n 1. Insert an element");
        printf("\n 2. Preorder Traversal");
        printf("\n 3. Exit");
        printf("\n\n Enter your option : ");
        scanf("%d", &option);
        switch (option) {
            case 1:
                printf("\n Enter the value of the new node : ");
                scanf("%d", &val);
                tree = insert(tree, val);
                break;
            case 2:
                printf("\n The elements of the tree are : \n");
                preorder(tree);
                break;
        }
    } while (option != 3);
    getch();
    return 0;
}
struct node* insert(struct node* tree, int val) {
    struct node *ptr, *nodeptr, *parentptr;
    ptr = (struct node*)malloc(sizeof(struct node));
    ptr->data = val;
    ptr->left = NULL;
    ptr->right = NULL;
    if (tree == NULL) {
        tree = ptr;
        tree->left = NULL;
        tree->right = NULL;
    } else {
        nodeptr = tree;
        parentptr = NULL;
        while (nodeptr != NULL) {
            parentptr = nodeptr;
            if (val < nodeptr->data)
                nodeptr = nodeptr->left;
            else
                nodeptr = nodeptr->right;
        }
        if (val < parentptr->data)
            parentptr->left = ptr;
        else
            parentptr->right = ptr;
    }
    return tree;
}
void preorder(struct node* tree) {
    if (tree != NULL) {
        printf("%d\t", tree->data);
        preorder(tree->left);
        preorder(tree->right);
    }
}

1. Why does ptr show as 50 after malloc when inserting 50?

This is almost certainly a debugger display quirk or a mix-up between what the pointer stores and what it points to. Here's the breakdown:

  • ptr = (struct node *)malloc(sizeof(struct node)); allocates a block of heap memory the size of your struct node, then returns the starting address of that block. This address is what gets stored in ptr—so ptr itself holds a memory address (like 0x7f9b12345678), not the value 50.
  • Right after this line, you run ptr->data = val; (with val being 50). This sets the data field of the newly allocated struct to 50.
  • Many debuggers, when showing a pointer to a struct, automatically display the value of the struct's first member (since the pointer points to the start of the struct, which aligns with the first member). So when you check ptr in the debugger, it's likely showing you ptr->data (50) instead of the actual memory address stored in ptr.

To confirm this, you could add a quick debug print:

ptr = (struct node *)malloc(sizeof(struct node));
printf("ptr's actual address: %p\n", ptr); // Prints the memory address
ptr->data = val;
printf("ptr->data value: %d\n", ptr->data); // Prints 50

2. When you do parentptr=NULL;, are you modifying the pointer variable itself or the content it points to?

You're modifying the pointer variable parentptr itself. Let's clarify the key difference:

  • A pointer variable (like parentptr) stores a memory address. When you write parentptr = NULL;, you're setting that stored address to NULL—meaning parentptr no longer points to any valid memory location.
  • If you wanted to modify the content that parentptr points to, you'd need to use the dereference operator (*) or arrow operator (->). For example:
    • *parentptr = some_node_struct; (overwrites the entire struct it points to)
    • parentptr->data = 100; (modifies the data field of the struct it points to)

In your code, setting parentptr = NULL; initializes it to a safe "empty" state before entering the loop, where you later assign it to point to existing nodes with parentptr = nodeptr;.

内容的提问来源于stack exchange,提问作者Chris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 14:27:45