简体   繁体   中英

Assigning a pointer in content of a pointer

In the code, we can see that a pointer is assigned in *new_node . But in C *new_node means content of new_node . So, what is the reason for it & why isn't it creating any problem?

Node *create_node(int item, Node *next)
{
    Node *new_node = (Node *)malloc(sizeof(Node));      //isn't it receiving the pointer as content of(*new_node) new_node?
    if (new_node == NULL) {
        printf("Error! Could not crate a new Node\n");
        exit(1);
    }

    new_node->data = item;
    new_node->next = next;
}

Node *new_node = (Node *)malloc(sizeof(Node));

This allocates new dynamic memory for new element of Node struct. And base address of the allocated memory is stored in new_node.

Now, new_node points to a new memory but that memory is empty/garbage. It doesn't contain any useful information about the node. So we need to fill the necessary information it that structure to make it useful.

`new_node->data = item;`
 new_node->next = next;

These lines copy the data to the allocated memory of new node and link the new node with other nodes.

NOTE: Your code snippet doesn't have return statement.

In an expression *new_node means “the object pointed to by new_node .” However, Node *new_node = (Node *)malloc(sizeof(Node)); is a declaration, not an expression statement, and the text *new_node in it is not an expression.

The first part of the declaration, Node *new_node , says “ new_node is a pointer to a Node .” The second part of the declaration, = (Node *)malloc(sizeof(Node)) , says “initialize new_node to (Node *)malloc(sizeof(Node)) . The = in this is not an assignment, and this is not an assignment expression. It is a syntax used in declarations for specifying an initial value for the object being defined. The object being defined is new_node , not *new_node .

This is different syntax between declarations and assignments, and you will have to become accustomed to it. Node *new_node = foo; initializes new_node to foo , but *new_node = foo; sets *new_node to foo .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM