Thread: dynamic array of struct within dynamic array of struct

  1. #1
    Registered User
    Join Date
    Apr 2010
    Posts
    6

    dynamic array of struct within dynamic array of struct

    Hey

    Here's an example of how I've been allocating structs:

    Code:
    typedef struct outer {
      char n;
      inner *b;
    } outer;
    
    typedef struct inner {
      float foo;
      int bar;
    } inner;
    
    int i, j;
    outer *A = malloc(sizeof(outer) * 100);
    for(i = 0; i < 100; i++)
    {
      A[i].b = malloc(sizeof(inner) * 1000);
    }
    and it seems to work ok. I was wondering what this would look like in memory though - I'm assuming that each inner *b array will be scattered. So my question is, does this reduce performance, and is it possible to allocate a single dynamic block for the whole outer *A structure?

    Many thanks
    Gib

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Code:
    struct inner *block = malloc( rows * cols * sizeof *block );
    for( x = 0; x < rows; x++ )
        outer[ x ]->inner = block + (cols * x);
    That looks about right.


    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    Registered User
    Join Date
    Apr 2010
    Posts
    6
    Hey thanks for the reply. So that would create an inner memory block, is it possible to create an outer memory block?

  4. #4
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Yeah, just do it like you initially did. Otherwise you'll have to explain clearer what you want.

    Quzah.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 7
    Last Post: 02-25-2010, 11:38 AM
  2. array of struct pointers
    By simo_mon in forum C Programming
    Replies: 4
    Last Post: 05-11-2009, 08:34 PM
  3. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 10:33 AM
  4. Replies: 4
    Last Post: 03-18-2003, 06:30 PM
  5. Hi, could someone help me with arrays?
    By goodn in forum C Programming
    Replies: 20
    Last Post: 10-18-2001, 09:48 AM