Thread: Can you have a 2D array of structures?

  1. #1
    Registered User
    Join Date
    Dec 2006
    Posts
    6

    Can you have a 2D array of structures?

    I just read that 2D arrays can only be of type char, int, or double.

    I have a structure that has 3 int variables. Is it possible to store this structure in each element of the array?

    Thanks.

  2. #2
    Ethernal Noob
    Join Date
    Nov 2001
    Posts
    1,901
    or classes, yes.

  3. #3
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >or classes, yes.
    A 2D array of classes is a great deal harder though.

    >Is it possible to store this structure in each element of the array?
    Yes, though you'll find the syntax has been complicated a bit due to extra levels of membership:
    Code:
    #include <stdio.h>
    
    struct blah {
      int a, b, c;
    };
    
    int main ( void )
    {
      struct blah feh[2][2] = {
        {
          {1,2,3},
          {4,5,6},
        },
        {
          {10,11,12},
          {13,14,15},
        }
      };
      int i, j;
    
      for ( i = 0; i < 2; i++ ) {
        for ( j = 0; j < 2; j++ )
          printf ( "(%d,%d,%d)", feh[i][j].a, feh[i][j].b, feh[i][j].c );
        printf ( "\n" );
      }
    
      return 0;
    }
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How To Declare and Dynamically Size a Global 2D Array?
    By groberts1980 in forum C Programming
    Replies: 26
    Last Post: 11-15-2006, 09:07 AM
  2. Class Template Trouble
    By pliang in forum C++ Programming
    Replies: 4
    Last Post: 04-21-2005, 04:15 AM
  3. Array of Structures: Sorting
    By Drainy in forum C Programming
    Replies: 3
    Last Post: 04-13-2005, 09:55 AM
  4. 2d array of structures
    By spudtheimpaler in forum C Programming
    Replies: 2
    Last Post: 03-01-2004, 03:17 PM
  5. how to pass 2D array into function..?
    By IngramGc in forum C++ Programming
    Replies: 2
    Last Post: 10-21-2001, 08:41 AM