Structures and dynamically allocated arrays

This is a discussion on Structures and dynamically allocated arrays within the C Programming forums, part of the General Programming Boards category; Hi, I'm a novice when it comes to programming. Right now I'm in college taking my first class on C++, ...

  1. #1
    Registered User
    Join Date
    Apr 2009
    Posts
    7

    Structures and dynamically allocated arrays

    Hi, I'm a novice when it comes to programming. Right now I'm in college taking my first class on C++, but our first homework assignment is in C.

    Anyways, the first programming assignment is fairly large and I've been working on it for a few days now.

    However, there's a certain part of the program where I'd love to utilize structures and dynamically allocated arrays for a specific purpose.

    I created a test program in C to kinda test out what I want to do...but I can't get it to compile. (If it doesn't compile, then surely it won't work in the grand scheme of things.)

    I would be grateful if anyone can point me in the right direction and help me find a solution for what I want to accomplish.

    Basically I'm trying to create a structure that contains a dynamically allocated array of structures, with each of these structures containing a dynamically allocated array of integers. So far I've been unsuccessful in getting something like this to compile (I use g++ if that matters)...

    Code:
    
    #include <stdio.h>
    #include <stdlib.h>
    
    // I want to create a "parent structure"
    // that is capable of holding a dynamically allocated
    // array of "child structures"
    //
    // each of these "child structures" would then hold
    // a dynamically allocated array of integers..
    
    
    // "child structure"
    typedef struct {
            int *numbers; // dynamically allocated array of ints
    } child_structure;
    
    // "parent structure"
    typedef struct {
            child_structure *items; // dynamically allocated array of child stucts
    } parent_structure;
    
    int
    main(void)
    {
            parent_structure test;
    
            int N, n;
    
            // first i dynamically allocate the array of child structures...
    
            test.items = (child_structure *)malloc(sizeof(child_structure) *N);
    
           // then i dynamically allocate the array of integers in each of child structures
           // ... at least that's what i'm trying to do!
    
            test.items.numbers = (int *)malloc(sizeof(int) *n);
    
            return (0);
    }
    I've fiddled around a bit...but I can't get it to compile. What am I doing wrong? Is there some kind of looping involved?

    Thanks in advance for the help.

  2. #2
    Registered User
    Join Date
    Sep 2004
    Location
    California
    Posts
    3,246
    Code:
    test.items.numbers = (int *)malloc(sizeof(int) *n);
    items is a pointer, so you must dereference it accordingly.
    Code:
    test.items->numbers = (int *)malloc(sizeof(int) *n);
    bit∙hub [bit-huhb] n. A source and destination for information.

  3. #3
    Registered User ssharish2005's Avatar
    Join Date
    Sep 2005
    Location
    Cambridge, UK
    Posts
    1,682
    Look at my inlines for comments

    Code:
    int main(void)
    {
            parent_structure test;
    
            int N, n;  
            // the values are initialised. The would be a major problem while dynamically allocating
            // N = n = 10;
            
            // DO NOT typecast the return of malloc. It already returns of type void *
            // Always check for the return value of malloc. 
            // if( ( test.items = malloc( sizeof( child_structure ) * N ) == NULL ) print( ERROR );
            // else print( PASS );
            test.items = (child_structure *)malloc(sizeof(child_structure) *N);
            
            // You cant do this, because of the operator precidences. 
            // test.items->numbers = malloc( sizeof( int ) * n );
            // And error handling here. VERY IMPORTANT!
            test.items.numbers = (int *)malloc(sizeof(int) *n);
            
            getchar();
            return (0);
    }
    ~ssharish
    Life is like riding a bicycle. To keep your balance you must keep moving - Einstein

  4. #4
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Couple of things: there is no purpose to casting malloc in C:
    Code:
    test.items = (child_structure *)malloc(sizeof(child_structure) *N);
    Also: you have not initialized N or n to any value!

    Next: What bithub says is true UNLESS you actually want "items" to be a " dynamically allocated array of ints". Look:
    Code:
    parent_structure test;
    One struct, with a member, items, which is supposed to be an array. But
    Code:
    test.items = malloc(sizeof(child_structure) *N);
    test.items.numbers = (int *)malloc(sizeof(int) *n);
    That's not an array! You want:
    Code:
    for (i=0; i<N; i++) {
         test.items[i].numbers = malloc(sizeof(int) *n);
    }
    Get it?

    You can do it the other way, but then you cannot access elements of test.items via array[subscripting] -- you must use pointer arithmetic on each element. Also, you would have to malloc test.items N*n*sizeof(int).
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  5. #5
    Registered User
    Join Date
    Apr 2009
    Posts
    7
    Thank you everyone for the swift and very helpful input!

    MK27 your advice on using the for loop made perfect sense! I was already thinking that some kind of loop was needed, but wasn't sure...but since I plan to access the arrays using subscripting, that was the info I needed.

    Quick question, you guys said that in C you don't need to cast the mallocs...but is there any harm in doing it anyway?

    The reason I'm asking is because I'll be implementing a lot of these kinds of structures in my programming assignment, and my professor requires us to submit our assignment by turning in the source code. He said that the TA's will be strictly using g++ to compile all our programs and grade them. If it doesn't compile then we lose points.

    The thing is, if I don't typecast the mallocs, then it'll compile just fine in gcc, but it won't compile in g++. If I typecast them, then it compiles in g++.

  6. #6
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by Bandizzle View Post
    The thing is, if I don't typecast the mallocs, then it'll compile just fine in gcc, but it won't compile in g++. If I typecast them, then it compiles in g++.
    I guess that is the answer then. No, it will not do any harm AFAIK.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  7. #7
    Registered User ssharish2005's Avatar
    Join Date
    Sep 2005
    Location
    Cambridge, UK
    Posts
    1,682
    >Quick question, you guys said that in C you don't need to cast the mallocs...but is there any harm in doing it anyway?

    Read this

    ~ssharish
    Life is like riding a bicycle. To keep your balance you must keep moving - Einstein

  8. #8
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,620
    Quote Originally Posted by Bandizzle View Post
    Thank you everyone for the swift and very helpful input!

    MK27 your advice on using the for loop made perfect sense! I was already thinking that some kind of loop was needed, but wasn't sure...but since I plan to access the arrays using subscripting, that was the info I needed.

    Quick question, you guys said that in C you don't need to cast the mallocs...but is there any harm in doing it anyway?

    The reason I'm asking is because I'll be implementing a lot of these kinds of structures in my programming assignment, and my professor requires us to submit our assignment by turning in the source code. He said that the TA's will be strictly using g++ to compile all our programs and grade them. If it doesn't compile then we lose points.

    The thing is, if I don't typecast the mallocs, then it'll compile just fine in gcc, but it won't compile in g++. If I typecast them, then it compiles in g++.
    You will want to stick with one way, since C does not require it and it might just hide a grave error, but in C++, it is required, and the pitfall that exists in C does not exist either, so it is safe.
    Since you are a C++ programmer, though, I suppose I should advise you to cast the return and compile with a C++ compiler.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 60
    Last Post: 01-09-2009, 12:09 PM
  2. Replies: 2
    Last Post: 11-26-2008, 09:25 AM
  3. Replies: 10
    Last Post: 05-18-2006, 11:23 PM
  4. dynamic arrays and structures
    By godofbabel in forum C++ Programming
    Replies: 1
    Last Post: 10-13-2002, 03:45 PM

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