🎙 Free live masterclass · Sun, 29 Nov, 7:00 pm IST · Java Full Stack roadmap Register free →
Skills101
← Quiz: Dynamic Memory: all 10 questions

Quiz: Dynamic Memory · Question 6 of 10

What does this print? (code)

What does this print?

#include <stdio.h>
#include <stdlib.h>
struct Node { int data; struct Node *next; };
struct Node *push(struct Node *head, int v) {
    struct Node *n = malloc(sizeof *n);
    n->data = v;
    n->next = head;
    return n;
}
int main(void) {
    struct Node *head = NULL;
    for (int i = 1; i <= 3; i++) head = push(head, i);
    for (struct Node *p = head; p != NULL; p = p->next) printf("%d ", p->data);
    printf("\n");
    while (head) { struct Node *t = head->next; free(head); head = t; }
    return 0;
}
  1. A.1 2 3
  2. B.3 2 1
  3. C.1
  4. D.3
Answer & explanation

Correct answer: 3 2 1

Each new node is added at the front, so the last value pushed (3) is printed first.

Can you get the rest right without peeking?

Take the timed Quiz: Dynamic Memory quiz free. Pass it to earn XP and count towards your certificate.

Start the quiz →