Declaring sizeless 2 dimensional array

This is a discussion on Declaring sizeless 2 dimensional array within the C Programming forums, part of the General Programming Boards category; Hi Im a newbie in C. But i know fortran very well. I try things i do in fortran in ...

  1. #1
    Registered User
    Join Date
    Apr 2012
    Posts
    1

    Declaring sizeless 2 dimensional array

    Hi
    Im a newbie in C. But i know fortran very well. I try things i do in fortran in c. I'm trying to declare a 2 dimensional matrix globally without specific sizes. Later im planing to allocate it according to input. I can do this

    float a[]; or this a[10] or this a[10][10]

    But i cant do this

    float a[][] or this a[2][] or this a[][3]

    Im trying to do something like

    real :: a(:,: ) (in fortran)

    Can you show me how to declare and allocate according to input?

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,499
    If you don't know the size until runtime, you do this
    Code:
    double **array;
    int row, col;
    // initialise row/col somehow
    array = malloc( row * sizeof(*array);
    for ( r = 0 ; r < row ; r++ ) {
      array[r] = malloc( col * sizeof(*array[r]);
    }
    // do stuff
    
    // when you're done
    for ( r = 0 ; r < row ; r++ ) {
      free(array[r]);
    }
    free(array);
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  3. #3
    Registered User
    Join Date
    Mar 2011
    Posts
    546
    the alternative that has a lot less complexity to it, and less management of pointers is to allocate a single block of data and compute the array index yourself.
    Question 6.16

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. declaring a multidimensional array
    By ca2004 in forum C++ Programming
    Replies: 4
    Last Post: 07-15-2010, 02:25 PM
  2. Declaring an array of classes...
    By Tozar in forum C++ Programming
    Replies: 11
    Last Post: 10-28-2006, 10:37 AM
  3. Replies: 1
    Last Post: 04-25-2006, 12:14 AM
  4. Declaring array ..
    By winsonlee in forum C Programming
    Replies: 5
    Last Post: 04-24-2004, 05:00 AM
  5. declaring an array of CPoints
    By swordfish in forum C++ Programming
    Replies: 1
    Last Post: 09-16-2001, 07:35 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21