Thread: Sintaxis for multidimensional array initialization

  1. #1
    Registered User
    Join Date
    Feb 2008
    Posts
    147

    Sintaxis for multidimensional array initialization

    I know how to property initialize a 1 dimensiona array, i.e.:
    Code:
    int x[3] = {0, 1 , 2};
    But how can I initialize de values of :

    Code:
    int x[3][3] = {?????}
    or
    Code:
    int x[2][4] = {???????}

  2. #2
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Quote Originally Posted by Kempelen View Post
    I know how to property initialize a 1 dimensiona array, i.e.:
    Code:
    int x[3] = {0, 1 , 2};
    But how can I initialize de values of :

    Code:
    int x[3][3] = {?????}
    or
    Code:
    int x[2][4] = {???????}
    Like this:

    Code:
    int x[][] = {
       {1, 2, 3},
       {4, 5, 6},
       {7, 8, 9}
    };
    In the initialization process, the number of rows and columns will be counted up for you, if you leave the square braces, empty. You can do this only ONCE, after that, you usually use a loop:

    Code:
    for(row = 0, yourVariable = 1; row < MaxRows; row++)  {
       for(col = 0; col < MaxCols; col++)   {
          x[row][col] = yourVariabe++;
       }
    }
    Last edited by Adak; 05-27-2008 at 02:26 AM.

  3. #3
    Technical Lead QuantumPete's Avatar
    Join Date
    Aug 2007
    Location
    London, UK
    Posts
    894
    The syntax for initialising a 2D array is as follows:

    Code:
    int my_array[][] = { {1,2,3}, {2,3,4}, {3,4,5} };
    QuantumPete
    "No-one else has reported this problem, you're either crazy or a liar" - Dogbert Technical Support
    "Have you tried turning it off and on again?" - The IT Crowd

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Array initialization with int variable
    By tsantana in forum C++ Programming
    Replies: 5
    Last Post: 03-31-2009, 02:48 PM
  2. question about multidimensional arrays
    By richdb in forum C Programming
    Replies: 22
    Last Post: 02-26-2006, 09:51 AM
  3. Array initialization has me dumbfounded.
    By chad_crider in forum C++ Programming
    Replies: 5
    Last Post: 02-23-2006, 11:13 PM
  4. Difference between array initialization
    By 3saul in forum C Programming
    Replies: 2
    Last Post: 02-05-2006, 11:51 PM
  5. Basic Array Initialization in C
    By Unregistered in forum C Programming
    Replies: 3
    Last Post: 02-18-2002, 06:41 PM