Thread: referencing structure variables

  1. #1
    Registered User sballew's Avatar
    Join Date
    Sep 2001

    referencing structure variables

    I am trying to make sure I got the referencing of structures, especially nested structure variables understood. Please look over the following declared structures and let me know if my answer to a - f questions are on target or not. Thanks.

    Given the following:

    struct point { int x, y;};

    struct shape {

    int shape_kind; /* RECTANGLE or CIRCLE */
    struct point center; /* coordinates of center */
    union {
    struct {
    int length, width;
    } rectangle;
    struct {
    int radius;
    } circle;
    } u;
    } s;

    Which of the following are legal AND safe?
    Which are legal though maybe unsafe?
    Which are illegal ?

    (a) s.shape_kind = RECTANGLE /* legal and safe */
    (b) = 10; /* legal and safe */
    (c) s.length = 25; /* not legal */
    should be :
    s.u.rectangle.length = 25;
    (d) s.u.rectangle.width = 8; /* legal and safe */
    (e) = 5; /* legal but maybe not safe */
    (f) s.u.radius = 5; /* not legal */
    should be : = 5;

    I would appreciate a quick response as I am being tested today over this.

    Sue B.

    dazed and confused

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    > Which of the following are legal AND safe?
    - it compiles
    - and you're consistent about whether you're using a circle or a rectangle

    > Which are legal though maybe unsafe?
    - it compiles
    - but you are inconsistent about whether its a circle or a rectangle.

    > Which are illegal ?
    - it does not compile.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. basic question about global variables
    By radeberger in forum C++ Programming
    Replies: 0
    Last Post: 04-06-2009, 12:54 AM
  2. Replies: 15
    Last Post: 09-30-2008, 02:12 AM
  3. esbo's data sharing example
    By esbo in forum C Programming
    Replies: 49
    Last Post: 01-08-2008, 11:07 PM
  4. passing structure arrays to functions?
    By bem82 in forum C Programming
    Replies: 3
    Last Post: 10-30-2006, 06:17 AM
  5. referencing C structure elements in assembly
    By BigAl in forum C Programming
    Replies: 7
    Last Post: 09-10-2001, 03:19 PM