Thread: array of structs

  1. #1
    Registered User
    Join Date
    May 2009
    Posts
    72

    array of structs

    Hi All

    I tried to construct an array of structs, but it doesn't compile

    Code:
    #include <stddef.h>
    #include <stdlib.h>
    #include <regex.h>
    #include <stdio.h>
    #include <string.h>
    
    struct Abc {
      int *x ;
    } *st ;
    
    int main(void) {
      st = malloc( 2 * sizeof(*st) ) ;
      st[0] = (struct Abc*)malloc(sizeof(struct Abc) ) ;
      st[1] = (struct Abc*)malloc(sizeof(struct Abc) ) ;
    }
    I guess I do something fundamentally wrong here! Any suggestions ?

    thnx
    LuCa

  2. #2
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Try this.
    Code:
    #include <stddef.h>
    #include <stdlib.h>
    
    struct Abc {
      int *x ;
    } ;
    
    int main(void) {
      struct Abc **st = malloc( 2 * sizeof(*st) ) ;
      st[0] = (struct Abc*)malloc(sizeof(**st) ) ;
      st[1] = (struct Abc*)malloc(sizeof(**st) ) ;
      return 0;
    }
    That creates an array of arrays with an Abc**.

    You can also do this.
    Code:
    #include <stddef.h>
    #include <stdlib.h>
    
    struct Abc {
      int *x ;
    } ;
    
    int main(void) {
      struct Abc *st = malloc( 2 * sizeof(*st) ) ;
      return 0;
    }
    Then st[0] is one element, and st[1] is another element. It's just that I've created an array of structures, not an array of pointers to dynamically allocated structures.
    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.

  3. #3
    Registered User
    Join Date
    May 2009
    Posts
    72
    wow, thats fast, thanks a lot! I guess I still have to get used to pointers to pointers!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 07-11-2008, 07:39 AM
  2. question about multidimensional arrays
    By richdb in forum C Programming
    Replies: 22
    Last Post: 02-26-2006, 09:51 AM
  3. Replies: 41
    Last Post: 07-04-2004, 03:23 PM
  4. array of structs initialization - PLZ help...
    By Vanya in forum C++ Programming
    Replies: 2
    Last Post: 12-11-2002, 08:10 PM
  5. Pointer to Array of Structs
    By Unregistered in forum C Programming
    Replies: 2
    Last Post: 03-06-2002, 08:34 AM