Thread: Accessing structures contained in structures

  1. #1
    Registered User
    Join Date
    Apr 2002
    Posts
    1

    Accessing structures contained in structures

    Given the following:

    struct year{
    int month;
    int day;
    int year;
    };

    struct person{
    char fname[15];
    char lname[15];
    struct year birthday;
    struct person *next;
    };

    struct person *current, *start;

    Would you be able to allocate memory using the following:

    start=(struct person *)malloc(sizeof(struct person));
    current = start;
    Will this include memory for the year structure contained in the person structure?

    Would you be able to access a member of birthday with the following:

    birth_month = current->birthday.month

    I receive a segmentation fault error when the program tries to read data into the year structure:
    ("%s", current->birthday.year);

    Thanks in advance

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >Would you be able to allocate memory using the following:
    Yes, but a better way would be:
    start = malloc ( sizeof *start );

    >Will this include memory for the year structure contained in the person structure?
    Yes.

    >Would you be able to access a member of birthday with the following:
    Yes.

    >("%s", current->birthday.year);
    Is this a call to scanf? Because birthday.year is an int and you are trying to read a string into it. Try this to get rid of the bug:
    scanf ( "%d", &start->birthday.year );

    -Prelude
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 07-11-2008, 07:39 AM
  2. accessing an array of structures
    By creative in forum C Programming
    Replies: 4
    Last Post: 12-27-2007, 12:52 PM
  3. Help on accessing structures using 'gets'
    By phil1p in forum C Programming
    Replies: 11
    Last Post: 10-27-2005, 04:56 PM
  4. Accessing members of structures
    By Nutshell in forum C Programming
    Replies: 6
    Last Post: 02-03-2002, 12:10 PM
  5. Methods for Sorting Structures by Element...
    By Sebastiani in forum C Programming
    Replies: 9
    Last Post: 09-14-2001, 12:59 PM