LearnFrenzy
Sign in Take a free test

Structures, Unions, Enums · Predict the Output · Question 5

Struct copy with a pointer member (shallow copy) Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

What is the output of the following C program on a 64-bit system?

main.c
#include <stdio.h>

struct box {
    int *p;
    int v;
};

int main(void) {
    int shared = 1;
    struct box a = {&shared, 1};
    struct box b = a;
    *b.p = 50;
    b.v = 99;
    printf("%d %d %d\n", *a.p, a.v, b.v);
    return 0;
}
  • A 1 1 99
  • B 50 99 99
  • C 1 99 99
  • D 50 1 99 Correct
Correct Answer: Option D

b = a copies the address in p, so both point to shared: writing 50 through b changes what a sees. v is a plain int, so b has its own copy.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links