Thread: declaring 2d arrays

  1. #1
    Registered User
    Join Date
    Jun 2002
    Posts
    3

    declaring 2d arrays

    I am trying to declare a 2d array with a integer as the size the integer is sent from another function.

    Is this possible?
    because i can't get it to work!

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    > Is this possible?
    It is in C++
    And will be when your compiler supports the latest C99 standard

    But until then, you need this
    Code:
    #include <stdlib.h>
    void foo ( int size ) {
      int **arr;
      int i;
    
      // allocate a 2D array
      arr = malloc( sizeof(int*) * size );
      for ( i = 0 ; i < size ; i++ ) arr[i] = malloc( sizeof(int) * size );
    
      // use arr as  arr[row][col]
      // as if you had declared int arr[size][size];
    
      // free the allocated array
      for ( i = 0 ; i < size ; i++ ) free( arr[i] );
      free( arr );
    }

  3. #3
    Registered User Zeeshan's Avatar
    Join Date
    Oct 2001
    Location
    London, United Kingdom
    Posts
    226
    can only be achieved using dynamic allocation

    i.e. using malloc/free for C
    or using new/delete for C++

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. 2D Array's, assigning chars.
    By gman89 in forum C Programming
    Replies: 9
    Last Post: 04-26-2008, 11:03 PM
  2. returning 2D arrays
    By ... in forum C++ Programming
    Replies: 2
    Last Post: 09-02-2003, 12:28 PM
  3. Initialising 2D and 3D arrays
    By fry in forum C++ Programming
    Replies: 5
    Last Post: 08-01-2002, 04:34 AM
  4. Reading 2d arrays from file?
    By Ringhawk in forum C++ Programming
    Replies: 3
    Last Post: 01-17-2002, 09:05 PM
  5. how can i pass 2d arrays
    By Unregistered in forum C++ Programming
    Replies: 5
    Last Post: 11-02-2001, 07:33 AM