Nested Structures

This is a discussion on Nested Structures within the C Programming forums, part of the General Programming Boards category; Hello, I need help accesing a structure: Code: typedef struct _SOME_DATA { int index; int descriptor; struct _KEYS *keys; struct ...

  1. #1
    eDD
    eDD is offline
    Registered User
    Join Date
    Aug 2009
    Posts
    1

    Nested Structures

    Hello, I need help accesing a structure:

    Code:
    typedef struct _SOME_DATA
    {
        int index;
        int descriptor;
        struct _KEYS *keys;
        struct _SOME_DATA *next;
    } SOME_DATA;
    
    typedef struct _KEYS
    {
        char *key1;
        char *key2;
    } KEYS;
    
    typedef SOME_DATA *ptr;
    typedef SOME_DATA *list;
    And i want to do something like this:
    Code:
    char *ptrkey1;
    char *ptrkey2;
    ptr = next;
    ptrkey1 = (char *)malloc(strlen(function_parameter) * sizeof(char));
    strcpy(ptrkey1, function_parameter_KEY.key1);
    // Program breaks here
    strcpy((char *)&next->keys->key1, ptrkey1);
    Has anyone an idea?, thanks in advance!!!

  2. #2
    Making mistakes
    Join Date
    Dec 2008
    Posts
    476
    Yes. Declare KEYS before SOME_DATA. Or put a forward declaration there:

    Code:
    struct _KEYS;
    
    typedef struct _SOME_DATA
    {
        int index;
        int descriptor;
        struct _KEYS *keys;
        struct _SOME_DATA *next;
    } SOME_DATA;
    
    typedef struct _KEYS
    {
        char *key1;
        char *key2;
    } KEYS;
    
    typedef SOME_DATA *ptr;
    typedef SOME_DATA *list;
    Code:
    ptrkey1 = (char *)malloc(strlen(function_parameter) * sizeof(char));
    You shouldn't cast malloc to char *. That would be easier. and sizeof(char) is always 1, so you can drop it. The most fatal error is that you forgot the terminating NUL character - it also needs a byte. And you could directly copy from function_parameter_KEY.key1 to next->keys->key1

    --> No & at the beginning. That's probably why it breaks
    Last edited by Brafil; 08-25-2009 at 05:47 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Nested Structures Possible?
    By thetinman in forum C++ Programming
    Replies: 6
    Last Post: 09-05-2007, 12:22 PM
  2. Nested Structures - User Input
    By shazg2000 in forum C Programming
    Replies: 2
    Last Post: 01-09-2005, 10:53 AM
  3. Nested Structures
    By Thantos in forum C Programming
    Replies: 2
    Last Post: 12-07-2003, 03:34 PM
  4. Nested structures
    By Supar in forum C++ Programming
    Replies: 2
    Last Post: 04-03-2003, 09:27 PM
  5. Nested structures
    By Garfield in forum C Programming
    Replies: 8
    Last Post: 10-08-2001, 01:11 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21