'Assignment to Heap Allocated Memory
I was writing a singly-linked list in C and cannot understand this following code.
#include <stdlib.h>
typedef struct ListNode {
int val;
struct ListNode* next;
} ListNode;
int main() {
/*Say I allocate this list to say 1->2->3->4->NULL*/
ListNode* node = malloc(sizeof(ListNode));
ListNode* n1 = node; // An ordinary pointer
ListNode* n_heap = malloc(sizeof(ListNode)); // A heap allocated pointer
n_heap = node->next; // 2->3->4->NULL
n1->next = NULL;
}
Now from the above example, I had assumed that n_heap to be NULL as well. But even after n1->next = NULL;, n_heap is still 2->3->4->NULL. So is the node->next copied to n_heap? or is it that n_heap now points to the original heap located node->next, and the n1->next now set to NULL? Does this mean node wasn't initially the owner of node->next data?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
