ProgrammingHard
Which C statement is correct for a node with an int field v and a next pointer, allocated and initialised to v = 7 with no next node?
- A. struct N *n = malloc(sizeof *n); if (n) { n->v = 7; n->next = NULL; }
- B. struct N *n = malloc(sizeof(struct N *)); n->v = 7; n->next = NULL;
- C. struct N n = malloc(sizeof n); n.v = 7;
- D. struct N *n = malloc(sizeof n); n->v = 7; n->next = n;
Correct answer: A. struct N *n = malloc(sizeof *n); if (n) { n->v = 7; n->next = NULL; }
sizeof *n gives the node size, the result is checked for NULL, and the next pointer is set. The other versions allocate a pointer's size, misuse malloc's result type, or make a self-loop.
More C Programming questions
- A doubly linked list stores prev pointers. How many pointer fields must change to insert a new node between two adjacent nodes A and B?
- A singly linked list of N = 10^6 nodes must answer 10^6 queries for the value at position k. Which approach is correct and fast enough?
- A function frees an entire list and then sets head = NULL. Why is setting head to NULL useful?
- Which kind of list makes it O(1) to delete a node given only a pointer to that node?
- In a singly linked list, which operation takes O(1) time when a pointer to the head is given?
- Two pointers walk a linked list: fast goes two nodes per step, slow goes one. The list has an even number of nodes N = 8 and no cycle…