Thread: Initializing a 2D array dynamically allocated

  1. #1
    Registered User
    Join Date
    Feb 2011
    Posts
    2

    Initializing a 2D array dynamically allocated

    I'm working with 2D arrays so that I can perform many calculations with them, just as matrices with numbers on them. Right now I change the dimensions of the matrices within the code, so I know what the dimensions are.
    I created a dynamically allocated 2d array, but I can't figure out how to initialize it. For instance:

    Code:
    int ROW=2;
    int COL=2;
    
    int main()
    {
    	float **mat1=(float **)malloc(ROW*COL*sizeof(float *));
    
    	mat1[ROW][COL]= { {5.3, 7.4},{1.1, 3.7} };
    
    .
    .
    .
    Trying to initialize the array this way, I get an error from the compiler, which says: "expected expression before "{" token ". I need to find a way to initialize the whole array with a single instruction, any help would greatly be appreciated.

    Thanks in advance!

  2. #2
    Registered User
    Join Date
    Oct 2008
    Location
    TX
    Posts
    2,059
    malloc() storage for all the elements before proceeding to initialize it.

  3. #3
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    If you get rid of the malloc on the first line, then specify float mat1... on the second line it should work.

    If you insist upon using malloc, you will need to initialize it in loops.

  4. #4
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Did you include stdlib.h?

    There is no need (and some risk) to casting the return from malloc().

    You have (apparently), allocated a pointer to a 2D array, but you have not yet allocated the pointers for each row of the array:

    Code:
    for(i = 0; i < NumberOfRowsYouWant; i++) 
      array[i] = malloc(columnsYouHave * sizeof(float));  //not float * for this one
    When you are done, free the row pointers first, and then the array pointer, (IOW, free them in reverse of the order you created them in).

    An example:
    Code:
    /* dynamically creates a 2D array of pointers, in C */
    
    #include <stdio.h>
    #include <stdlib.h>
    
    //void allocate2D(double **dat2, int nrows, int ncols); 
    double** allocate2D(int nrows, int ncols);
    
    int main() {
      int i,j, rows, cols; 
      double **dat;
    
      printf("\n\n\n How many rows do you want?\n ");
      scanf("%d", &rows);
      (void) getchar();
      printf(" How many columns do you want?\n ");
      scanf("%d", &cols);
      (void) getchar();
    
      dat = allocate2D(rows, cols);
      for(i=0;i<rows;i++) {
        for(j=0;j<cols;j++) {
          dat[i][j] = i+j;
        }
      }
      for(i=0;i<rows;i++) {
          for(j=0;j<cols;j++) 
            printf("\n%.3lf", dat[i][j]);
      }
       
      for(i=0;i<rows;i++)
        free(dat[i]);
      free(dat);
    
      printf("\n\t\t\t    press enter when ready");
      (void) getchar();
      return 0;
    }
    double** allocate2D(int nrows, int ncols) {
      int i;
      double **dat2;
      /*  allocate array of pointers  */
      dat2 = malloc( nrows*sizeof(double*));
         
      if(dat2==NULL) {
        printf("\nError allocating memory\n");
        exit(1);
      }
      /*  allocate each row  */
      for(i = 0; i < nrows; i++) {
        dat2[i] = malloc( ncols*sizeof(double));
      }
      if(dat2[i-1]==NULL) {
        printf("\nError allocating memory\n");
        exit(1);
      }
      return dat2;
    }
    Last edited by Adak; 02-01-2011 at 12:59 PM.

  5. #5
    Registered User
    Join Date
    Feb 2011
    Posts
    2
    Thanks for your quick answers.
    I removed the cast, and allocated pointers for each row of the array. Then I freed the pointers.
    But in the statement for statement:mat1[ROW][COL]= { {5.3, 7.4},{1.1, 3.7} }; , there is still the same error: "expected expression before "{" token "

    Is it really possible to initialize this way? or it is necessary a loop as some people mentioned.
    Thanks

  6. #6
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    No, it's not possible. You can only use that style of initializer when you declare the variable:
    Code:
    int foo[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } };
    That's OK. This is not:
    Code:
    int foo[ 2 ][ 2 ];
    foo = { { 1, 2 }, { 3, 4 } };
    Quzah.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Dynamically allocate 2D array of ints
    By steals10304 in forum C Programming
    Replies: 3
    Last Post: 10-24-2009, 08:31 PM
  2. How To Declare and Dynamically Size a Global 2D Array?
    By groberts1980 in forum C Programming
    Replies: 26
    Last Post: 11-15-2006, 09:07 AM
  3. passing a 2dim dynamically allocated array to a funct
    By agerealm in forum C++ Programming
    Replies: 3
    Last Post: 03-10-2004, 06:55 PM
  4. Replies: 5
    Last Post: 12-05-2002, 02:27 AM
  5. Hi, could someone help me with arrays?
    By goodn in forum C Programming
    Replies: 20
    Last Post: 10-18-2001, 09:48 AM

Tags for this Thread