Thread: Dynamic structure with array and array count

  1. #1
    Registered User
    Join Date
    Mar 2006
    Posts
    158

    Question Dynamic structure with array and array count

    I don't know if the title was the best choice but I dunno what else to write there... Here's my problem:

    I have the following structures:

    Code:
    struct example1 {
        int size;
        int items[20];
    }
    
    struct example2 {
        int size;
        int items[100];
    }
    Both items array on both the structures will have only numbers between 1 and 50 (for instance), if they have 0 it means it is a position in the array that it's not being used. So, if size is like 15 (in the first structure) I only go from positions 0 and 14 in the array and ll the others will only have zeros.

    My question is: is, somehow, possible to have only one structure instead of those 2 but defining the items array maximum size dynamically while declaring a variable?

    Or with some other approach? I just didn't want to use 2 or more structures for this kind of stuff just cause they are not all of the same size and I didn't want to allocate lots of memory (items[100]) when I only need 20 for some variables, know what I mean?

    So, is it possible?

  2. #2
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    Define your struct like this:

    Code:
    struct exampleA
    {
    	int size;
    	int *items;
    };
    When you create it, for example:

    Code:
    struct exampleA exa;
    exa.size = 100;
    exa.items = malloc(sizeof(*(exa.items))*exa.size);
    Replace 100 with whatever you want the size to be (for example replace it with a function parameter).

    For all intents and purposes, items will now function as an array. Just remember to specifically free it.

  3. #3
    Registered User
    Join Date
    Mar 2006
    Posts
    158
    I'll try that, thanks...

    However, that do you mean by "Just remember to specifically free it."? I'm asking this cause I've already use malloc and realloc on lots of code and never free any memory and I believe that's not a good choice.

    Any guide/tutorial/faq you could point me to to learn more about when (and how) should I free whatever I allocate memory?

  4. #4
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Basically, you just free() dynamically allocated memory when you're finished with it.

    You also have to be careful to free() memory that you would soon have no references to. So if a function allocates some memory but doesn't return it, free the memory before the function returns; otherwise, the only pointer to the memory will be lost and will not be able to free it at a later point in time.

    free() takes a pointer which malloc() or realloc() returned as an argument. It doesn't change the pointer, but after the free() call you can no longer access the pointer.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  5. #5
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    Code:
    int *x = malloc(sizeof(*x));
    
    x = 5;
    printf("x = %d\n");
    
    free(x); /* Memory can be reclaimed now later on. */
    If you don't free the memory, and you're allocating a lot of these structs, you may end up with a situation where you run out of memory. You should get into the habbit of free()ing memory that you allocate.

    One school of thought is that in some cases, you should not free() memory, but this does not appear to be one of those cases.

  6. #6
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Did you mean this?
    Code:
    *x = 5;
    printf("x = %d\n", x);
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  7. #7
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    Wow, that's bad.... Remind me to proof-read my code about 3 more times before I post. lol...

  8. #8
    Registered User
    Join Date
    Mar 2006
    Posts
    158
    Alright, I'll give this a try and check my whole code for memory allocation and implement the free() function one by one one every situation and check if the code runs anyway...

    I'll post something later on if I still have any issues with this...

    Thanks a lot.

  9. #9
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    What operating system are you using? Valgrind is quite nice for detecting memory leaks if you think you've fixed them all, but it only runs under Linux. There are other leak checkers for Windows and other platforms, but I have no experience with them.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  10. #10
    Registered User
    Join Date
    Mar 2006
    Posts
    158
    I'm using linux, and valgrind is on portage at the stable tree (gentoo). How do I use it?

  11. #11
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    better yet
    Code:
    *x = 5;
    printf("x = %d\n", *x);
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  12. #12
    Registered Abuser
    Join Date
    Jun 2006
    Location
    Toronto
    Posts
    591
    I think you may be interested in what is called a "Flexible array member". Basically it is an array declared at the end of structure with no set size:
    Code:
    struct foo
    {
       int size;
       char arr[];
    }
    Then when you go to allocate memory for your structure, you allocate the size of the struct plus the number of bytes you want to allocate for the array at the end. I'm not too sure about the details (the most I've seen it used is in winapi), but I believe this functionality is defined in C99, more information: Flexible array members

  13. #13
    Registered User
    Join Date
    Mar 2006
    Posts
    158
    Isn't that what MacGyver suggested?

  14. #14
    Woof, woof! zacs7's Avatar
    Join Date
    Mar 2007
    Location
    Australia
    Posts
    3,459
    Better yet again
    Code:
    int *x = NULL;
    
    if((x = malloc(sizeof(*x)) == NULL)
    {
        perror("Malloc failed");
        exit(1);
    }
    
    *x = 5;
    printf("x = %d\n", *x);
    
    free(x);
    x = NULL;

  15. #15
    Registered Abuser
    Join Date
    Jun 2006
    Location
    Toronto
    Posts
    591
    Quote Originally Posted by Nazgulled View Post
    Isn't that what MacGyver suggested?
    No: one way you are allocating memory for the struct, then explicitly allocating memory for the array; in the other way you are allocating memory for both at the same time (as well, there are also other suttle differences).

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Dynamic Array Allocation function
    By P4R4N01D in forum C++ Programming
    Replies: 6
    Last Post: 05-15-2009, 02:04 AM
  2. Multi-dimensional dynamic array - performance
    By melkor445 in forum C++ Programming
    Replies: 15
    Last Post: 10-07-2007, 04:17 AM
  3. Structure array problem
    By Birdhaus in forum C++ Programming
    Replies: 2
    Last Post: 11-21-2005, 09:59 PM
  4. two-dimensional dynamic array of pointers to classes
    By Timo002 in forum C++ Programming
    Replies: 4
    Last Post: 04-21-2005, 06:18 AM
  5. Class Template Trouble
    By pliang in forum C++ Programming
    Replies: 4
    Last Post: 04-21-2005, 04:15 AM