Thread: dynamic mem alloc of 2-d arrays

  1. #1
    Registered User hankspears's Avatar
    Join Date
    Mar 2002
    Posts
    14

    dynamic mem alloc of 2-d arrays

    So, anyone know how to create a 2-d array using calloc? It seems to have been overlooked in my book.

  2. #2
    ....
    Join Date
    Aug 2001
    Location
    Groningen (NL)
    Posts
    2,380
    You could make an array of pointers and let each element be an array.

    http://www.cs.cf.ac.uk/Dave/C/node11...00000000000000

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Like so
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    #define ROWS    5
    #define COLS    20
    
    int main ( ) {
        int test[ROWS][COLS];
        int **p;
        int row, col;
    
        /* allocate it */
        p = calloc( ROWS, sizeof(int*) );
        for ( row = 0 ; row < ROWS ; row++ ) {
            p[row] = calloc( COLS, sizeof(int) );
        }
    
        /* use it */
        for ( row = 0 ; row < ROWS ; row++ ) {
            for ( col = 0 ; col < COLS ; col++ ) {
                test[row][col] = p[row][col];
            }
        }
        /* free it */
        for ( row = 0 ; row < ROWS ; row++ ) {
            free(p[row]);
        }
        free(p);
    
        return 0;
    }

  4. #4
    Registered User hankspears's Avatar
    Join Date
    Mar 2002
    Posts
    14
    OK, I thought there would be a nice easy command to do it, but I guess not.
    thanks for your help...

  5. #5
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >OK, I thought there would be a nice easy command to do it
    How is that not easy?

    -Prelude
    My best code is written with the delete key.

  6. #6
    Registered User hankspears's Avatar
    Join Date
    Mar 2002
    Posts
    14
    The key word there is actually command (singular)

  7. #7
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > The key word there is actually command
    There is a one-liner, but it only works if COLS is a compile-time constant.

    Perhaps you were thinking of some bloat language which does everything for you.

    At some point, you've got to get into it at start doing things for yourself.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 16
    Last Post: 01-01-2008, 04:07 PM
  2. processing dynamic arrays
    By Mario F. in forum C++ Programming
    Replies: 9
    Last Post: 06-04-2006, 11:32 AM
  3. Dynamic (Numeric) Arrays
    By DavidB in forum C++ Programming
    Replies: 5
    Last Post: 05-03-2006, 07:34 PM
  4. dynamic arrays and structures
    By godofbabel in forum C++ Programming
    Replies: 1
    Last Post: 10-13-2002, 03:45 PM