ProgrammingHard
A function gets a pointer to a linked list and must keep the list unchanged but needs to walk it twice. Which kind of pointer parameter is right?
- A. struct N **head, because the caller must receive a copy
- B. struct N head, passing the node by value
- C. const struct N *head, so the walk cannot modify the nodes through the pointer
- D. void *head, with no type checking
Correct answer: C. const struct N *head, so the walk cannot modify the nodes through the pointer
A const pointer documents and enforces that the walk reads only. The other forms change the calling convention or lose the type.
More C Programming questions
- A program keeps 10^5 small objects in a free list of pointers. Which operation is O(1) per object?
- int arr = malloc(5 sizeof arr); for (int i = 0; i < 5; i++) arr[i] = i i; int q = arr + 2; printf("%d", q[1]); What is printed?
- struct N { int v; struct N next; } a = NULL; for (int i = 1; i <= 3; i++) { struct N n = malloc(sizeof n); n->v = i; n->next = a; a = n; }…
- Two pointers p and q point into the same block allocated with malloc(10 sizeof(int)). Which subtraction is defined?
- A linked list of length n is reversed in place with a loop. How much extra memory is used?
- unsigned int h = 0; for (const char p = "ab"; p; p++) h = h 31 + p; printf("%u", h); What is printed (ASCII, 32-bit unsigned)?