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?

  1. A. struct N *n = malloc(sizeof *n); if (n) { n->v = 7; n->next = NULL; }
  2. B. struct N *n = malloc(sizeof(struct N *)); n->v = 7; n->next = NULL;
  3. C. struct N n = malloc(sizeof n); n.v = 7;
  4. 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

Exams that ask this topic