Thread: Make an array of arrays

  1. #1
    Registered User
    Join Date
    Aug 2007
    Posts
    52

    Make an array of arrays

    Hi, I'm writing C code for a project and I would like to know (if it's possible) how to make an array of arrays. I mean I want to place a bidimensional array inside each one of the elements of an unidimensional array.
    Thank you in advance.

  2. #2
    The superhaterodyne twomers's Avatar
    Join Date
    Dec 2005
    Location
    Ireland
    Posts
    2,273
    1D integer array: int array1d[10];
    access via: array1d[index];

    2D integer array: int array2d[10][10];
    access via: array2d[indexY][indexX];

    3D integer array: int array3d[10][10][10];
    access via: array3d[inxexZ][indexY][indexX];

    Etc.

  3. #3
    Registered User C_ntua's Avatar
    Join Date
    Jun 2008
    Posts
    1,853
    It is a bit more complicated if you want a fairly big array, which isn't uncommon for 3D arrays. In that case you will need to dynamically allocate memory, because statically allocated memory can overflow the stack. An example is Z, X, Y being > 1000.

    Do that like this for a Z*Y*X 3d-array:
    Code:
    int ***array;
    for (int z = 0; z < Z; ++z) {
        array[z] = malloc(Y *  sizeof(*int));
        for (int y = 0; y < Y; ++y)
             array[z][y] = malloc (X * sizeof(int));
    }
    and access normally with array[z][y][x];

    (though I believe there is a bit better solution, which kind of bored to think atm)

  4. #4
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Code:
    T (*array)[3d_size][2d_size] = malloc(1d_size * 2d_size * 3d_size * sizeof(T));
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 6
    Last Post: 11-09-2006, 03:28 AM
  2. Arrays, how to find if some number is the element of an array.
    By InvariantLoop in forum C++ Programming
    Replies: 14
    Last Post: 03-18-2006, 02:43 AM
  3. Quick question about SIGSEGV
    By Cikotic in forum C Programming
    Replies: 30
    Last Post: 07-01-2004, 07:48 PM
  4. Type and nontype parameters w/overloading
    By Mr_LJ in forum C++ Programming
    Replies: 3
    Last Post: 01-02-2004, 01:01 AM
  5. Array of Character Arrays
    By Unregistered in forum C Programming
    Replies: 3
    Last Post: 02-09-2002, 06:07 PM