Thread: instances of a structure in a structure

  1. #1
    Registered User
    Join Date
    Oct 2001
    Posts
    25

    instances of a structure in a structure

    Hi,

    I have the following structure, made up of four structures:-

    Code:
    struct customer_details {
        struct1;
        struct2;
        struct3;
        struct bundle_info bundle_data;
    }thisCustomer;
    the structure bundle_info is made up as follows....

    Code:
    struct bundle_info {
        char x;
        char y;
    }
    This has four instances...

    Code:
    struct bundle_info bundle1;
    etc.
    Now my question is thus...how do I assign values to one of these instances?

    I thought it would be...

    memcpy(thisCustomer.bundle1.x, buf, 5)

    where buf is a character array.

    However, this gives the error "bundle1 is not a member of thisCustomer".

    Any ideas?

    Bill

    [code][/code]tagged by Salem

  2. #2
    Me want cookie! Monster's Avatar
    Join Date
    Dec 2001
    Posts
    680
    I'm not sure what you want, but here an example:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    struct bundle_info 
    {
       char x;
       char *y;
       char z[100];
    };
    
    struct customer_details 
    {
       int nr;
       struct bundle_info bundle_data[10]; /* 10 instances */
    };
    
    int main(void)
    {
       customer_details thisCustomer;
    
       thisCustomer.nr = 1;
       thisCustomer.bundle_data[0].x = 'a';
       thisCustomer.bundle_data[9].x = 'j';
       /* y is a character pointer so we need to allocate space before copying */
       thisCustomer.bundle_data[0].y = strdup("Hello Y");
       strcpy(thisCustomer.bundle_data[0].z, "Hello Z");
    
       printf("%s\n", thisCustomer.bundle_data[0].y);
       printf("%s\n", thisCustomer.bundle_data[0].z);
       free(thisCustomer.bundle_data[0].y);
       return 0;
    }
    Hope it helps...

    Cheers,
    Monster

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem referencing structure elements by pointer
    By trillianjedi in forum C Programming
    Replies: 19
    Last Post: 06-13-2008, 05:46 PM
  2. Replies: 5
    Last Post: 02-14-2006, 09:04 AM
  3. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  4. Serial Communications in C
    By ExDigit in forum Windows Programming
    Replies: 7
    Last Post: 01-09-2002, 10:52 AM
  5. C structure within structure problem, need help
    By Unregistered in forum C Programming
    Replies: 5
    Last Post: 11-30-2001, 05:48 PM